在 Python 中,为什么使用 `eval` 时没有出现警告?

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

以下代码按预期打印警告:

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

但是,当使用eval时,不会出现警告信息:

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

为什么警告在这两种情况下表现不同?

Why do warnings behave differently in these two situations?

他们没有。来自 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()')

或:

import warnings

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

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

两者都显示来自 eval('f()') 调用的警告:

# 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)