
Fill in
Decorators with Arguments
What if a decorator needs settings, like @retry(3)? Then retry(3)
must return a decorator. That's three layers:
import functools
def repeat(times): # 1. takes the settings
def decorator(func): # 2. takes the function
@functools.wraps(func)
def wrapper(*args, **kwargs): # 3. runs each call
return [func(*args, **kwargs) for _ in range(times)]
return wrapper
return decorator
@repeat(2) # same as: chant = repeat(2)(chant)
def chant():
return "lumos"
chant() # ['lumos', 'lumos']
Read it from the outside in: repeat(2) runs once and hands back
decorator, which wraps chant. The inner layers can all see times
thanks to closures.
Assignment
Fill in the ___ to finish retry(times). The wrapper should call
the function up to times times. As soon as one call succeeds, return
its result. If every attempt raises, re-raise the last exception.
Fill in the ___ to finish retry(times). The wrapper should call
the function up to times times. As soon as one call succeeds, return
its result. If every attempt raises, re-raise the last exception.
main.py Python sleeping
Press Run to try your code, then Check to test it.