当我们在Python2中导入_库时,我们对它进行了编码,以引发一次弃用警告。这是代表代码
我们的_库/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/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)
然后,当我们导入库并调用该函数时,如下所示:
调用_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警告中显式指定消息将防止为其他弃用警告设置'once
过滤器
但事实并非如此?这是为什么?如何在不使用CatchWarnings或reset warnings的情况下使现有代码工作
如果我将参数warning更改为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,
)
不过,我忘了defualt不会显示弃用警告。它们必须特别设置为显示,我在这里没有这样做
相关问题 更多 >
编程相关推荐