7

The following code prints a warning, as expected:

>>> import warnings
>>> def f():
...     warnings.warn('Deprecated', DeprecationWarning)
...     print('In function f()')
... 
>>> f()
__main__:2: DeprecationWarning: Deprecated
In function f()

However, when using eval, the warning message does not appear:

>>> eval('f()')
In function f()

Why do warnings behave differently in these two situations?

1
  • Im assuming that Eval might be running that function in a mini-instance that does not have the warnings module present, but thats just me guessing. Commented Mar 21, 2019 at 14:48

1 Answer 1

2

Why do warnings behave differently in these two situations?

They don't. From the docs:

Repetitions of a particular warning for the same source location are typically suppressed.

import warnings

def f():
    warnings.warn("dep", DeprecationWarning)
    print('in f')

f()
warnings.resetwarnings()
eval('f()')

Or:

import warnings

def f():
    warnings.warn("dep", DeprecationWarning)
    print('in f')

# don't call f()
#f()
eval('f()')

Both show the warning from the eval('f()') call:

# with warnings.resetwarnings() between f() and eval('f()')
in f
/home/gir/local/dev/pcws/local/main.py:7: DeprecationWarning: dep
in f
  warnings.warn("dep", DeprecationWarning)
/home/gir/local/dev/pcws/local/main.py:7: DeprecationWarning: dep
  warnings.warn("dep", DeprecationWarning)

# without calling f() directly
/home/gir/local/dev/pcws/local/main.py:5: DeprecationWarning: dep
in f
  warnings.warn("dep", DeprecationWarning)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.