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

从Python模块导入的装饰器不工作,python,python-2.7,ipython,decorator,Python,Python 2.7,Ipython,Decorator,我正在尝试对iPython笔记本中定义或导入的函数使用以下装饰器: 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(*a

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

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
中定义了decorator。当我以这种方式使用装饰器时:

import utils #from utils import deprecated

@utils.deprecated
def test():
    print 'Brokolice'
然后运行
test()
会打印“Brokolice”,但不会给出任何警告。然而,当我在iPython中定义decorator时,我得到了所需的弃用警告


我使用的是Python2.7,一般来说,我对修饰符或Python还不是很熟悉,但在这种情况下,我不知道哪里出了问题,因为如果导入修饰符失败,我可能会遇到某种错误。

尝试在
导入警告下方配置
警告。过滤器警告('always')

In [1]: import test

In [2]: test.test()
warning
utils.py:12: DeprecationWarning: Call to deprecated function test.
  category=DeprecationWarning)
Brokolice
这将打印默认情况下由python2.7隐藏的DeprecationWarning警告。有关详细信息,请参阅

对于您的问题“知道为什么“return func(*args,**kwargs)”行也会被打印出来吗?”

这只是为了可读性


长度(线)应该感谢你,这是伟大的作品!我没想到问题出在“警告”上。但是,该警告现在有一个新行:
utils.py:69:DeprecationWarning:Call to deprecated function test。return func(*args,**kwargs)
,位于装饰器中警告下方的一行。知道为什么“return func(*args,**kwargs)”行也会被打印出来吗?:-)嗯,我想你可以像这里建议的那样配置showwarning或formatwarning方法好的,很好!非常感谢你!
python -Wd test.py  #  -Wdefault