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:

  1. The decorated function can be called n times. Each call passes all arguments through and returns the original result.
  2. After n calls, a call raises RuntimeError(f"{func.__name__} is out of charges") without calling the original function.
  3. The wrapper has an attribute remaining: the charges left. It starts at n and goes down by one per successful call.
  4. Use functools.wraps so the name and docstring are kept.