跳转到主要内容

扩展warnings.warn的callee参数

项目描述

扩展warnings.warn的callee参数

当你有一些库,有一些过时的函数 X,你可以在 warnings.warn 上使用 stacklevel=2 参数来显示调用 X 的例程的文件名和行号

但是如果你有一个框架,它通过插件或显式注册调用用户提供的代码,那么 stacklevel 无法帮助你抱怨过时的返回值。

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

警告通常为 PendingDeprecationWarningDeprecationWarning 或它们的子类。

例如,如果你有两个文件 p0.pyp2.py,它们的内容都相同

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

还有一个文件 p1.py

class PlugIn
def status(self)

return [‘ok’] # 此插件已更新

并且这些文件位于 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.warning-0.2.1.tar.gz (12.4 kB 查看哈希值)

上传时间 源代码

构建分发版本

ruamel.std.warning-0.2.1-py3-none-any.whl (3.6 kB 查看哈希值)

上传时间 Python 3

支持者