【发布时间】: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