在Python2中导入our_library时,我们对其进行了编码,以引发一次DeprecationWarning。这是代表代码。
our_library / 初始化 .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_library / some_module.py
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
过滤器。
但事实并非如此吗?这是为什么?如何在不使用CatchWarnings或重置警告的情况下使现有代码正常工作?
如果我将参数警告更改为FutureWarning,则可以看到。 为什么第一个simplefilter会基于类别而不是消息来阻止所有弃用消息?
更新:
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,
)
答案 0 :(得分:0)
没关系,我已经忘记了deprecation不会显示DeprecationWarnings。必须将它们专门设置为显示,这在这里我还没有做。