当我们在our_library中导入Python2时,我们已经将其编码为引发DeprecationWarning一次。这是代表代码。
our_library/init.py
def _py2_deprecation_warning():
py2_warning = ('Python2 support is deprecated and will be removed in '
'a future release. Consider switching to Python3.')
warnings.filterwarnings('once', message=py2_warning)
warnings.warn(message=py2_warning,
category=DeprecationWarning,
stacklevel=3,
)
def _python_deprecation_warnings():
if sys.version_info.major == 2:
_py2_deprecation_warning()
_python_deprecation_warnings()我们在our_library中反对函数中的参数。下面是代表代码:
我们的图书馆/某个模组.our
def some_function(new_param, deprecated_param):
if deprecated_param:
param_deprecation_msg = (
'The parameter "{}" will be removed in a future version of Nilearn.'
'Please use the parameter "{}" instead.'.format(deprecated_param,
new_param,
)
)
warnings.warn(category=DeprecationWarning,
message=param_deprecation_msg,
stacklevel=3)然后,当我们导入库并调用该函数时,如下所示:
calling_script.py
from our_library.some_module import some_function
some_function(deprecated_param)我们得到的是Python2 DeprecationWarning,而不是参数DeprecationWarning。
DeprecationWarning: Python2 support is deprecated and will be removed in a future release. Consider switching to Python3.
_python_deprecation_warnings()现在知道我可以通过使用with warnings.catch_warnings():或resetwarnings()来解决这个问题。但是,我认为在Python2警告中显式指定消息将防止为其他DeprecationWarnings设置'once筛选器。
然而,情况并非如此?WhHy就是这样,如何使我现有的代码在不使用CatchWarnings或重置警告的情况下工作呢?
如果将参数警告更改为FutureWarning,则可以看到。为什么第一个简单程序会根据类别而不是消息来阻止所有的弃用消息?
更新:with warnings.catch_warnings():似乎也不起作用。
def _py2_deprecation_warning():
py2_warning = ('Python2 support is deprecated and will be removed in '
'a future release. Consider switching to Python3.')
with warnings.catch_warnings():
warnings.filterwarnings('once', message=py2_warning)
warnings.warn(message=py2_warning,
category=DeprecationWarning,
stacklevel=3,
)发布于 2019-02-06 14:52:08
不过,我已经忘记了,DeprecationWarnings并不是通过贬义来显示的。它们必须特别设置为显示,而我在这里没有这样做。
https://stackoverflow.com/questions/54554532
复制相似问题