首页 > 解决方案 > 在 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,
                      )

标签: pythonwarnings

解决方案


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.


推荐阅读