
Checkpoint
Checkpoint: Charged Spells
Guild wands hold a limited number of charges. Each cast uses one. When a wand is empty, it refuses to cast.
You'll build this as a decorator with a setting, so any spell can be limited:
@charges(2)
def spark(colour):
return f"{colour} spark"
spark("blue") # 'blue spark'
spark.remaining # 1
spark("red") # 'red spark'
spark("gold") # RuntimeError: spark is out of charges
This checkpoint uses closures, nonlocal, a decorator factory
(three layers) and functools.wraps.
Assignment
Write charges(n), a decorator factory:
- The decorated function can be called
ntimes. Each call passes all arguments through and returns the original result. - After
ncalls, a call raisesRuntimeError(f"{func.__name__} is out of charges")without calling the original function. - The wrapper has an attribute
remaining: the charges left. It starts atnand goes down by one per successful call. - Use
functools.wrapsso the name and docstring are kept.
Write charges(n), a decorator factory:
- The decorated function can be called
ntimes. Each call passes all arguments through and returns the original result. - After
ncalls, a call raisesRuntimeError(f"{func.__name__} is out of charges")without calling the original function. - The wrapper has an attribute
remaining: the charges left. It starts atnand goes down by one per successful call. - Use
functools.wrapsso the name and docstring are kept.
main.py Python sleeping
Press Run to try your code, then Check to test it.