python - 在 warnings.simple_filter() 过滤器中指定消息基于类别而不是消息
问题描述
当我们在 Python2 中导入 our_library 时,我们已经对其进行了编码以引发一次 DeprecationWarning。这是代表代码。
我们的库/初始化.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)
然后当我们导入我们的库并调用该函数时,如下所示:
调用脚本.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():
or来解决这个问题resetwarnings()
。但是我认为在 Python2 警告中明确指定消息将阻止'once
为其他 DeprecationWarnings 设置过滤器。
然而事实并非如此?这是为什么?如何在不使用 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,
)
解决方案
Nevermind, I had forgotten that DeprecationWarnings are not displayed by defualt. They must specifically be set to be displayed, which I have not done here.
推荐阅读
- three.js - Threejs如何获取模型的最外层尺寸
- android - 将数据传递到服务器时进行深度链接
- reactjs - 无法访问从 JSON 解析的 JavaScript 对象属性
- rust - 为什么 while 不是 Rust 中的表达式
- python - scapy KeyError:RSNinfo
- sql - 在 Postgres sql 的 ORDER BY 中使用 LENGTH(计算列)
- jquery - 如何使用 Select2 插件删除 jQuery 中的空格
- javascript - 修改 JSON 对象中的特定值,返回具有修改值的对象的克隆版本?
- typescript - 从模块名称列表中推断函数参数类型
- c# - 如何在c#中显示向后计数并用逗号分隔