【问题标题】:Decorator imported from Python module not working从 Python 模块导入的装饰器不起作用
【发布时间】:2016-01-22 19:24:35
【问题描述】:

我正在尝试对在 iPython 笔记本中定义或导入到 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 中定义了装饰器。当我以这种方式使用装饰器时:

import utils #from utils import deprecated

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

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

我使用的是 Python 2.7,但我对装饰器或 Python 还不是很满意,但在这种情况下,我不知道出了什么问题,因为如果导入装饰器失败,我预计会出现某种错误。

【问题讨论】:

    标签: python python-2.7 ipython decorator


    【解决方案1】:
    python -Wd test.py  #  -Wdefault
    

    这将打印默认情况下被 python2.7 隐藏的 DeprecationWarning 警告。详情请见here

    对于您的问题“知道为什么会打印“return func(*args, **kwargs)”这一行吗?”。

    这只是为了可读性..

    长度(行)在 pep8 中应该

    【讨论】:

      【解决方案2】:

      尝试在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
      

      【讨论】:

      • 谢谢,这很好用!我没想到问题出在“警告”上。但是,警告现在有一个新行:utils.py:69: DeprecationWarning: Call to deprecated function test. return func(*args, **kwargs),它是装饰器中警告下方的一行。知道为什么还要打印“return func(*args, **kwargs)”行吗? :-)
      • mmm 我想你可以像这里建议的那样配置 showwarning 或 formatwarning 方法stackoverflow.com/questions/2187269/…
      • 好的,很好!非常感谢!
      猜你喜欢
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多