【发布时间】:2019-11-07 18:24:37
【问题描述】:
我在一些单元测试中使用函数装饰器来测试代码。但是,我发现这个装饰器会导致函数被调用两次(因此打印它的输出两次)。
我在某些函数返回错误的返回值后发现了这个错误,这种错误的返回值只有在函数被调用两次时才会发生。
#!/usr/bin/env python3
def decorate(func):
@wraps(func)
def inner(*args, **kwargs):
print("#" * 40)
print("Testing function {}".format(func.__name__))
print("Arguments passed: {} ".format(args))
print("Begin output of {}".format(func.__name__))
print("#" * 40)
try:
func(*args, **kwargs)
except Exception as e:
print("Error occured: {}".format(e))
print("#" * 40)
print("End of output of {}".format(func.__name__))
print("#" * 40)
print("\n" * 5)
return func(*args,**kwargs) #Error happens on this line here
return inner
#Add decorator to function definition.
@decorate
def asdf():
print("THIS SHOULD PRINT ONCE")
#Call function
asdf()
输出(与复制的间距完全相同):
########################################
Testing function asdf
Arguments passed: ()
Begin output of asdf
########################################
THIS SHOULD PRINT ONCE
########################################
End of output of asdf
########################################
THIS SHOULD PRINT ONCE
我想要的输出:
########################################
Testing function asdf
Arguments passed: ()
Begin output of asdf
########################################
THIS SHOULD PRINT ONCE
########################################
End of output of asdf
########################################
我正在尝试消除该函数的第二次调用。我知道我的错误在于装饰器,我只是找不到它。
【问题讨论】:
标签: python python-3.x python-decorators