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?
The warn() function defined in the ' warning ' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python. print ( 'Geeks !' )
eval() is considered insecure because it allows you (or your users) to dynamically execute arbitrary Python code. This is considered bad programming practice because the code that you're reading (or writing) is not the code that you'll execute.
Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library.
Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With