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

时间:2019-03-21 13:53:11

标签: python warnings 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()

为什么在这两种情况下警告的行为不同?

1 个答案:

答案 0 :(得分:2)

  

为什么在这两种情况下警告的行为不同?

他们没有。来自docs

  

针对同一源位置重复特定警告是   通常被抑制。

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)