自动重载和函数装饰器

时间:2018-04-13 20:59:32

标签: ipython decorator

我对装饰者来说相当新,但在带有装饰功能的交互式工作流程中遇到意外行为。最好通过示例解释(注意这些是jupyter笔记本中的所有单元格):

装饰者:

%%file testdec.py
def decorated(func):
    print("decorating")
    def wrapped(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapped

使用装饰器的地方:

%%file testmod.py
from testdec import decorated
@decorated
def thisfunc():
    print("old output")
def _thisfunc1():
    print("old output 1")
thisfunc1 = decorated(_thisfunc1)

我将使用以下内容来调用修饰函数:

from testmod import *
thisfunc()
thisfunc1()

输出:

decorating
decorating
old output
old output 1

现在使用:

更新testmod.py
%%file testmod.py
from testdec import decorated
@decorated
def thisfunc():
    print("new output")
def _thisfunc1():
    print("new output 1")
thisfunc1 = decorated(_thisfunc1)

再次调用函数:

thisfunc()
thisfunc1()

给出以下内容,请注意第一种方法的旧输出:

decorating
decorating
old output
new output 1

但是,明确地从这个模块重新导入:

from testmod import *
thisfunc()
thisfunc1()

结果:

new output
new output 1

理想情况下,@decorated函数(例如使用@而不是第二种方法)会像第二种方法那样透明地自动加载。我能做些什么来实现这个目标吗?装饰功能我缺少什么。现在,我们在交互式编辑时手动禁用装饰器,以获得自动重载的好处。

感谢。

0 个答案:

没有答案
相关问题