简体   繁体   English

从Python模块导入的装饰器无法正常工作

[英]Decorator imported from Python module not working

I am trying to use the following decorator on functions defined in or imported to iPython notebook: 我试图在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

I defined the decorator in utils.py . 我在utils.py定义了装饰器。 When I use the decorator this way: 当我以这种方式使用装饰器时:

import utils #from utils import deprecated

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

Then running test() prints 'Brokolice', but does not give any warning. 然后运行test()打印'Brokolice',但不给出任何警告。 However, when I define the decorator within iPython, I get the desired deprecated warning. 但是,当我在iPython中定义装饰器时,我得到了不希望的警告。

I am using Python 2.7 and I am not yet very comfortable with decorators or Python in general, but in this case, I have no idea what is wrong, as I would expect some kind of error if import of the decorator failed. 我正在使用Python 2.7,但对装饰器或Python总体上还不太满意,但是在这种情况下,我不知道出了什么问题,因为如果装饰器导入失败,我会期望某种错误。

Try configuring warnings.filterwarnings('always') below the import warnings 尝试在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

this will print the DeprecationWarning warnings which is hidden by python2.7 by default. 这将显示DeprecationWarning警告,该警告默认情况下被python2.7隐藏。 see here for details. 详情请参阅这里

And for your question "Any idea why is the line "return func(*args, **kwargs)" getting printed as well?". 对于您的问题“任何想法为什么“ return func(* args,** kwargs)”行也会被打印出来?”。

This is just for readability.. 这只是为了提高可读性。

length(line) should <= 80 in pep8 长度(线)应小于等于pep8中的80

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM