本文介绍了python标准库中的装饰器(@deprecated)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to mark routines as deprecated, but apparently there's no standard library decorator for deprecation. I am aware of recipes for it and the warnings module, but my question is: why is there no standard library decorator for this (common) task ?

其他问题:标准库中是否有标准修饰符?

Additional question: are there standard decorators in the standard library at all ?

推荐答案

以下是一些片段,从Leandro引用的片段中进行了修改:

Here's some snippet, modified from those cited by 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

因为在某些解释器中公开的第一个解决方案(不使用过滤器处理)可能会导致警告被禁止。

Because in some interpreters the first solution exposed (without filter handling) may result in a warning suppression.

这篇关于python标准库中的装饰器(@deprecated)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:42