Python 在调用前面而不是在定义前面应用decorator
我目前正在尝试使用decorators来实现功能,在我最终让AssertionError冒泡之前,在我的单元测试中等待一些assert调用 目前,我的装饰师如下所示:Python 在调用前面而不是在定义前面应用decorator,python,unit-testing,python-decorators,Python,Unit Testing,Python Decorators,我目前正在尝试使用decorators来实现功能,在我最终让AssertionError冒泡之前,在我的单元测试中等待一些assert调用 目前,我的装饰师如下所示: def waitUpTo(seconds): def decorator(assert_func_to_decorate): def wrapper(*args, **kwargs): for _ in range(seconds): print(da
def waitUpTo(seconds):
def decorator(assert_func_to_decorate):
def wrapper(*args, **kwargs):
for _ in range(seconds):
print(datetime.now())
try:
return(assert_func_to_decorate(*args,**kwargs))
except AssertionError:
time.sleep(1)
return(assert_func_to_decorate(*args,**kwargs))
return wrapper
return decorator
waitUpTo(3)(self.assertRegexpMatches)('notHello', r'Hello')
当我像这样调用和使用它时,它工作得非常好:
def waitUpTo(seconds):
def decorator(assert_func_to_decorate):
def wrapper(*args, **kwargs):
for _ in range(seconds):
print(datetime.now())
try:
return(assert_func_to_decorate(*args,**kwargs))
except AssertionError:
time.sleep(1)
return(assert_func_to_decorate(*args,**kwargs))
return wrapper
return decorator
waitUpTo(3)(self.assertRegexpMatches)('notHello', r'Hello')
但不知何故,这个电话往往会变得有点长。
有没有办法在实际调用函数之前而不是在定义函数之前使用@语法
理想情况下,这样的事情会很好:
@waitUpTo(3)
self.assertRegexpMatches('notHello', r'Hello')
不,没有办法做到这一点,@decorator语法专门用于方法/类/函数定义,而不是调用。嗯,好吧,我假设没有其他快捷方式或语法糖我可以使用,或者有没有?你可以把它分成两行:decordent\u func=decoratordeco\u argsfunc;装饰的函数参数。这还允许您例如将装饰分解为一个循环。除此之外,没有其他语法用于应用decorator。是的,我知道,但在本例中,decorator的参数会根据我要测试的内容而经常更改,这有点麻烦,但感谢您的推荐