python标准库中的装饰器(@deprecated)

您所在的位置:网站首页 @deprecated python标准库中的装饰器(@deprecated)

python标准库中的装饰器(@deprecated)

2023-05-18 10:34| 来源: 网络整理| 查看: 265

这是另一种解决方案:

该装饰器(实际上是装饰器工厂)允许您提供原因消息。通过提供源文件名和行号来帮助开发人员诊断问题也更有用。

编辑:此代码使用Zero的建议:用替换warnings.warn_explicit行warnings.warn(msg, category=DeprecationWarning, stacklevel=2),它打印函数调用站点而不是函数定义站点。它使调试更加容易。

EDIT2:此版本允许开发人员指定可选的“原因”消息。

import functools import inspect import warnings string_types = (type(b''), type(u'')) def deprecated(reason): """ This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. """ if isinstance(reason, string_types): # The @deprecated is used with a 'reason'. # # .. code-block:: python # # @deprecated("please, use another function") # def old_function(x, y): # pass def decorator(func1): if inspect.isclass(func1): fmt1 = "Call to deprecated class {name} ({reason})." else: fmt1 = "Call to deprecated function {name} ({reason})." @functools.wraps(func1) def new_func1(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn( fmt1.format(name=func1.__name__, reason=reason), category=DeprecationWarning, stacklevel=2 ) warnings.simplefilter('default', DeprecationWarning) return func1(*args, **kwargs) return new_func1 return decorator elif inspect.isclass(reason) or inspect.isfunction(reason): # The @deprecated is used without any 'reason'. # # .. code-block:: python # # @deprecated # def old_function(x, y): # pass func2 = reason if inspect.isclass(func2): fmt2 = "Call to deprecated class {name}." else: fmt2 = "Call to deprecated function {name}." @functools.wraps(func2) def new_func2(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn( fmt2.format(name=func2.__name__), category=DeprecationWarning, stacklevel=2 ) warnings.simplefilter('default', DeprecationWarning) return func2(*args, **kwargs) return new_func2 else: raise TypeError(repr(type(reason)))

您可以将此修饰符用于函数,方法和类。

这是一个简单的例子:

@deprecated("use another function") def some_old_function(x, y): return x + y class SomeClass(object): @deprecated("use another method") def some_old_method(self, x, y): return x + y @deprecated("use another class") class SomeOldClass(object): pass some_old_function(5, 3) SomeClass().some_old_method(8, 9) SomeOldClass()

你会得到:

deprecated_example.py:59: DeprecationWarning: Call to deprecated function or method some_old_function (use another function). some_old_function(5, 3) deprecated_example.py:60: DeprecationWarning: Call to deprecated function or method some_old_method (use another method). SomeClass().some_old_method(8, 9) deprecated_example.py:61: DeprecationWarning: Call to deprecated class SomeOldClass (use another class). SomeOldClass()

EDIT3:现在,此装饰器已成为不推荐使用的库的一部分:

Python包索引(PyPi) GitHub网站 阅读文档 推特

新的稳定版本v1.2.10🎉



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3