在调用前面而不是在定义前面应用decorator

2024-10-03 09:09:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试使用decorator来实现功能,在我最终让AssertionError冒泡之前,在我的单元测试中等待一些断言调用

目前,我的装饰师如下所示:

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')

Tags: toselfreturndefargsdecoratorassertwrapper