从 Python 模块导入的装饰器不工作

Decorator imported from Python module not working

我正在尝试对 iPython notebook 中定义或导入的函数使用以下装饰器:

import warnings

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.'''
    def new_func(*args, **kwargs):
        warnings.warn("Call to deprecated function {}.".format(func.__name__),
                  category=DeprecationWarning)
        return func(*args, **kwargs)
    new_func.__name__ = func.__name__
    new_func.__doc__ = func.__doc__
    new_func.__dict__.update(func.__dict__)
    return new_func

我在 utils.py 中定义了装饰器。当我这样使用装饰器时:

import utils #from utils import deprecated

@utils.deprecated
def test():
    print 'Brokolice'

然后 运行 test() 打印 'Brokolice',但不给出任何警告。但是,当我在 iPython 中定义装饰器时,我收到了所需的弃用警告。

我正在使用 Python 2.7,我对装饰器或一般来说 Python 还不是很满意,但在这种情况下,我不知道哪里出了问题,正如我所期望的那样如果装饰器导入失败,会出现某种错误。

尝试在 import warnings

下面配置 warnings.filterwarnings('always')
In [1]: import test

In [2]: test.test()
warning
utils.py:12: DeprecationWarning: Call to deprecated function test.
  category=DeprecationWarning)
Brokolice
python -Wd test.py  #  -Wdefault

这将打印默认情况下被 python2.7 隐藏的 DeprecationWarning 警告。有关详细信息,请参阅 here

关于你的问题 "Any idea why is the line "return func(*args, **kwargs)" getting printed as well?"。

这只是为了便于阅读..

长度(行)在 pep8 中应该 <= 80