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


127

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

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


13
现在有一个弃用
muon

11
我了解执行此操作的方法,但是来到这里是为了了解为什么它不在std lib中(我假设是OP的情况),并且对实际问题没有很好的答案
SwimBikeRun

4
为什么会如此频繁地发生,以至于问题得到数十个甚至没有试图回答该问题的答案,而积极地忽略诸如“我知道食谱”之类的东西?太疯狂了!
Catskul

1
@Catskul因为虚假的互联网积分。
Stefano Borini

1
您可以使用不推荐使用的库。
Laurent LAPORTE '19

Answers:


59

这是从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

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


14
为什么不使用functools.wraps而不是像这样设置名称和文档呢?
Maximilian 2015年

1
@Maximilian:进行了编辑以添加该代码,以免将来编写此代码时也避免做错该事
Eric

17
我不喜欢副作用(打开/关闭过滤器)。决定这不是装饰者的工作。
肯索(Kentzo)

1
打开和关闭过滤器可能会触发bugs.python.org/issue29672
gerrit

4
没有回答实际问题。
Catskul

44

这是另一种解决方案:

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

编辑:此代码使用Zero的建议:用替换warnings.warn_explicitwarnings.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:现在,此装饰器已成为不推荐使用的库的一部分:

新的稳定版本v1.2.10🎉


6
工程,以及-我更喜欢更换warn_explicit用线warnings.warn(msg, category=DeprecationWarning, stacklevel=2),其打印函数调用的位置,而不是函数定义的网站。它使调试更加容易。
2016年

您好,我想在GPLv3许可的库中使用您的代码段。您是否愿意根据GPLv3 或更宽松的许可来重新许可您的代码,以便我可以合法地这样做?
gerrit


1
我知道@LaurentLAPORTE。CC-BY-SO不允许在GPLv3中使用(因为类似共享位),这就是为什么我问您是否愿意特别在兼容GPL的许可证下发布此代码。如果没有,那很好,我不会使用您的代码。
Gerrit

2
没有回答实际问题。
Catskul

15

如muon所建议,您可以deprecation为此安装软件包。

deprecation库为您的测试提供了一个deprecated装饰器和一个fail_if_not_removed装饰器。

安装

pip install deprecation

用法示例

import deprecation

@deprecation.deprecated(deprecated_in="1.0", removed_in="2.0",
                        current_version=__version__,
                        details="Use the bar function instead")
def foo():
    """Do some stuff"""
    return 1

有关完整文档,请参见http://deprecation.readthedocs.io/


4
没有回答实际问题。
Catskul

1
注意PyCharm无法识别此问题
cz

11

我猜想原因是Python代码无法静态处理(就像C ++编译器所做的那样),您在实际使用某些东西之前不会得到警告。我认为用一堆消息“警告:此脚本的开发人员正在使用已弃用的API”来向脚本用户发送垃圾邮件不是一个好主意。

更新:但是您可以创建装饰器,它将原始功能转换为另一个。新功能将标记/检查开关,告知该功能已被调用,并且仅在将开关置于打开状态时显示消息。和/或在退出时,它可以打印程序中使用的所有不赞成使用的功能的列表。


3
当从模块导入功能时,您应该能够指示不赞成使用。装饰器将是一个正确的工具。
Janusz Lenar

@JanuszLenar,即使我们不使用该不推荐使用的功能,也会显示该警告。但是我想我可以用一些提示更新我的答案。
2013年

8

您可以创建一个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

谢谢,我正在使用它来将用户发送到正确的位置,而不仅仅是显示弃用消息!
德国Attanasio '18

3
没有回答实际问题。
Catskul

2

更新:我认为更好,当我们只为每行代码第一次显示DeprecationWarning时,以及当我们可以发送一些消息时:

import inspect
import traceback
import warnings
import functools

import time


def deprecated(message: str = ''):
    """
    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 first time and filter is set for show DeprecationWarning.
    """
    def decorator_wrapper(func):
        @functools.wraps(func)
        def function_wrapper(*args, **kwargs):
            current_call_source = '|'.join(traceback.format_stack(inspect.currentframe()))
            if current_call_source not in function_wrapper.last_call_source:
                warnings.warn("Function {} is now deprecated! {}".format(func.__name__, message),
                              category=DeprecationWarning, stacklevel=2)
                function_wrapper.last_call_source.add(current_call_source)

            return func(*args, **kwargs)

        function_wrapper.last_call_source = set()

        return function_wrapper
    return decorator_wrapper


@deprecated('You must use my_func2!')
def my_func():
    time.sleep(.1)
    print('aaa')
    time.sleep(.1)


def my_func2():
    print('bbb')


warnings.simplefilter('always', DeprecationWarning)  # turn off filter
print('before cycle')
for i in range(5):
    my_func()
print('after cycle')
my_func()
my_func()
my_func()

结果:

before cycle
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:45: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
aaa
aaa
aaa
aaa
after cycle
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:47: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:48: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa
C:/Users/adr-0/OneDrive/Projects/Python/test/unit1.py:49: DeprecationWarning: Function my_func is now deprecated! You must use my_func2!
aaa

Process finished with exit code 0

我们只需单击警告路径,然后转到PyCharm中的行。


2
没有回答实际问题。
Catskul

0

增强此答案由史蒂芬Vascellaro

如果使用Anaconda,请先安装deprecation软件包:

conda install -c conda-forge deprecation 

然后将以下内容粘贴到文件顶部

import deprecation

@deprecation.deprecated(deprecated_in="1.0", removed_in="2.0",
                    current_version=__version__,
                    details="Use the bar function instead")
def foo():
    """Do some stuff"""
    return 1

有关完整文档,请参见http://deprecation.readthedocs.io/


4
没有回答实际问题。
Catskul
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.