mercredi 18 février 2015

apply decorator in front of call and not in front of definition

I'm currently trying to use decorators to implement the functionality to wait for some assert calls in my unittests before i finally let the AssertionError bubble up.


Currently my decorator looks like this:



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


And it works quite well when i call and use it like this:



waitUpTo(3)(self.assertRegexpMatches)('notHello', r'Hello')


But somehow this calls tend to get a little bit long. Is there a way to use the @ syntax for this before the actual call to the function and not before the definition of it?


Ideally such a thing would be nice:



@waitUpTo(3)
self.assertRegexpMatches('notHello', r'Hello')

Aucun commentaire:

Enregistrer un commentaire