扩展warnings.warn的callee参数
项目描述
扩展warnings.warn的callee参数
当您有一个包含已弃用函数 X 的库时,您可以在 warnings.warn 上使用 stacklevel=2 参数来显示调用 X 的例程的文件名和行号
但如果您有一个通过插件或显式注册调用用户提供的代码的框架,那么 stacklevel 就无法帮助您对已弃用的返回值提出抱怨。
此库通过添加 callee 参数扩展了 warnings.warn。如果提供了此参数,则不应提供 stacklevel,并且 callee 的值应为引发警告的方法或函数。
警告通常为 PendingDeprecationWarning、DeprecationWarning 或其任一子类。
例如,如果您有两个文件 p0.py 和 p2.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.tar.gz 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 078f284834f4b2bb86c06c9567ab5d7156b120e02ca699e52d02eb8a03d834ec |
|
| MD5 | 7e0ba0f6a3ad75f3c2f01b1cde342b7c |
|
| BLAKE2b-256 | 0f3fb1806d5c68f713051707105cd109ec0f0dbaa70bdf84eb502d2717a999fd |
关闭
ruamel.std.warnings-0.3.0-py3-none-any.whl 的哈希值
| 算法 | 哈希摘要 | |
|---|---|---|
| SHA256 | 2d340805aaf70d39366daafd02d53fcfb9ec60f67e4e0c51450f934b259b8fff |
|
| MD5 | b70b4aa553fac223160b23929870b642 |
|
| BLAKE2b-256 | 466d3d01e94d98c04e07c2fa33ffa5c74022f5cbd96d5d00679a327440ea103a |