跳转到主要内容

扩展warnings.warn的callee参数

项目描述

扩展warnings.warn的callee参数

https://sourceforge.net/p/ruamel-std-warnings/code/ci/default/tree/_doc/_static/license.svg?format=raw https://sourceforge.net/p/ruamel-std-warnings/code/ci/default/tree/_doc/_static/pypi.svg?format=raw https://sourceforge.net/p/oitnb/code/ci/default/tree/_doc/_static/oitnb.svg?format=raw

当您有一个包含已弃用函数 X 的库时,您可以在 warnings.warn 上使用 stacklevel=2 参数来显示调用 X 的例程的文件名和行号

但如果您有一个通过插件或显式注册调用用户提供的代码的框架,那么 stacklevel 就无法帮助您对已弃用的返回值提出抱怨。

此库通过添加 callee 参数扩展了 warnings.warn。如果提供了此参数,则不应提供 stacklevel,并且 callee 的值应为引发警告的方法或函数。

警告通常为 PendingDeprecationWarningDeprecationWarning 或其任一子类。

例如,如果您有两个文件 p0.pyp2.py,它们都具有以下内容:

class PlugIn:
 def status(self):
     return {'result': 'ok'}

以及一个文件 p1.py

class PlugIn:
    def status(self):
        return ['ok'] # this plug-in has been updated

这些文件位于您的框架可以找到的 plug_ins 子文件夹中。然后运行

import sys
from pathlib import Path
from importlib import import_module
import ruamel.std.warnings
import warnings

class DictReturnPendingDeprecationWarning(PendingDeprecationWarning):
    pass

class Driver:
    def __init__(self):
        self.plug_ins = []

    def load_plug_ins(self):
        sys.path.append('plug_ins')
        for file_name in Path('plug_ins').glob('p*.py'):
            mod = import_module(file_name.stem)
            self.plug_ins.append(mod.PlugIn())

    def check_status(self):
        for p in self.plug_ins:
            retval = p.status()
            if isinstance(retval, dict):
                # assume dict
                warnings.warn(
                   'callable should return list, not dict',
                   DictReturnPendingDeprecationWarning,
                   callee=p.status,
                )
            else:
                pass  # assume list

warnings.simplefilter('once', PendingDeprecationWarning)

def doit():
    driver = Driver()
    driver.load_plug_ins()
    for idx in range(2):
        driver.check_status()
    warnings.warn('almost done', PendingDeprecationWarning)

doit()

将产生以下结果:

/tmp/plug_ins/p0.py:2: DictReturnPendingDeprecationWarning: callable should return list, not dict
  def status(self):
/tmp/plug_ins/p2.py:2: DictReturnPendingDeprecationWarning: callable should return list, not dict
  def status(self):
/tmp/tmp_00.py:40: PendingDeprecationWarning: almost done
  warnings.warn('almost done', PendingDeprecationWarning)

项目详情


下载文件

下载适合您平台的应用程序。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

ruamel.std.warnings-0.3.0.tar.gz (12.6 kB 查看哈希值)

上传时间 源码

构建分发

ruamel.std.warnings-0.3.0-py3-none-any.whl (3.9 kB 查看哈希值)

上传时间 Python 3

由以下支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面