首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据类别而不是消息在warnings.simple_filter()筛选器中指定消息

根据类别而不是消息在warnings.simple_filter()筛选器中指定消息
EN

Stack Overflow用户
提问于 2019-02-06 13:15:22
回答 1查看 51关注 0票数 0

当我们在our_library中导入Python2时,我们已经将其编码为引发DeprecationWarning一次。这是代表代码。

our_library/init.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
from our_library.some_module import some_function

some_function(deprecated_param)

我们得到的是Python2 DeprecationWarning,而不是参数DeprecationWarning。

代码语言:javascript
复制
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():似乎也不起作用。

代码语言:javascript
复制
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,
                      )
EN

回答 1

Stack Overflow用户

发布于 2019-02-06 14:52:08

不过,我已经忘记了,DeprecationWarnings并不是通过贬义来显示的。它们必须特别设置为显示,而我在这里没有这样做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54554532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档