我需要将例程标记为已弃用,但显然没有标准的库装饰器可供弃用。我知道它和警告模块的配方,但我的问题是:为什么这个(公共)任务没有标准库装饰器?
附加问题:标准库中是否有标准装饰器?
发布于 2015-05-15 15:24:28
以下是Leandro引用的代码片段:
import warnings
import functools
def deprecated(func):
"""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."""
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) # turn off filter
warnings.warn("Call to deprecated function {}.".format(func.__name__),
category=DeprecationWarning,
stacklevel=2)
warnings.simplefilter('default', DeprecationWarning) # reset filter
return func(*args, **kwargs)
return new_func
# Examples
@deprecated
def some_old_function(x, y):
return x + y
class SomeClass:
@deprecated
def some_old_method(self, x, y):
return x + y
因为在某些解释器中,暴露的第一个解决方案(没有过滤器处理)可能会导致警告抑制。
发布于 2018-02-06 05:50:52
您可以创建utils文件
import warnings
def deprecated(message):
def deprecated_decorator(func):
def deprecated_func(*args, **kwargs):
warnings.warn("{} is a deprecated function. {}".format(func.__name__, message),
category=DeprecationWarning,
stacklevel=2)
warnings.simplefilter('default', DeprecationWarning)
return func(*args, **kwargs)
return deprecated_func
return deprecated_decorator
然后导入弃用装饰器,如下所示:
from .utils import deprecated
@deprecated("Use method yyy instead")
def some_method()"
pass
https://stackoverflow.com/questions/2536307
复制相似问题