首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python标准库中的装饰符(特别是@deprecated)

python标准库中的装饰符(特别是@deprecated)
EN

Stack Overflow用户
提问于 2010-03-29 15:14:58
回答 2查看 94.8K关注 0票数 167

我需要将例程标记为已弃用,但显然没有标准的库装饰器可供弃用。我知道它和警告模块的配方,但我的问题是:为什么这个(公共)任务没有标准库装饰器?

附加问题:标准库中是否有标准装饰器?

EN

回答 2

Stack Overflow用户

发布于 2015-05-15 15:24:28

以下是Leandro引用的代码片段:

代码语言:javascript
复制
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

因为在某些解释器中,暴露的第一个解决方案(没有过滤器处理)可能会导致警告抑制。

票数 77
EN

Stack Overflow用户

发布于 2018-02-06 05:50:52

您可以创建utils文件

代码语言:javascript
复制
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

然后导入弃用装饰器,如下所示:

代码语言:javascript
复制
from .utils import deprecated

@deprecated("Use method yyy instead")
def some_method()"
 pass
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2536307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档