Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why do warnings not appear when using `eval`?

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?

like image 435
user200783 Avatar asked Mar 21 '19 13:03

user200783


People also ask

How do I enable warnings in Python?

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 !' )

Why you should never use eval in Python?

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.

Which method is used to display a warning message in Python?

Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library.

What does eval () do in Python?

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.


1 Answers

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)
like image 51
shmee Avatar answered Oct 18 '22 01:10

shmee