Scopes, Closures and Decorators · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: A running total with a closure ✓ Passed
Write make_accumulator(start=0) that returns a function add(value). Each call adds value to a running total (which begins at start) and returns the new total.
Use a closure (no classes, no globals). Accumulators created by separate calls must be independent.
def make_accumulator(start=0):
total = start
def add(value):
total = total + value
return total
return add
def test_basic():
"""adds values cumulatively"""
acc = make_accumulator()
assert acc(10) == 10
assert acc(5) == 15, "the total should carry over between calls"
def test_start():
"""respects the start value"""
acc = make_accumulator(100)
assert acc(1) == 101
def test_independent():
"""separate accumulators don't share state"""
a, b = make_accumulator(), make_accumulator()
a(1); a(2)
assert b(10) == 10, f"b should start from 0, got {b(0)}"
assert a(0) == 3
def test_is_closure():
"""total is a free variable of the returned function"""
acc = make_accumulator()
assert 'total' in acc.__code__.co_freevars
Hints (2)
- The starter raises
UnboundLocalError. Why doestotal = total + valuemaketotallocal toadd? - Declare
nonlocal totalinsideaddso the assignment re-binds the enclosing variable.
Show a solution
def make_accumulator(start=0):
total = start
def add(value):
nonlocal total
total += value
return total
return addExercise 2: A decorator factory that limits calls ✓ Passed
Write a decorator factory call_limit(n). A function decorated with @call_limit(n) works normally for its first n calls; after that, every call raises RuntimeError (without calling the original function).
Use functools.wraps so the decorated function keeps its __name__ and __doc__. Each decorated function has its own call count.
from functools import wraps
def call_limit(n):
def decorator(fn):
def inner(*args, **kwargs):
return fn(*args, **kwargs)
return inner
return decorator
def test_allows_n_calls():
"""the first n calls work and return the result"""
@call_limit(2)
def add(a, b):
return a + b
assert add(1, 2) == 3
assert add(b=5, a=1) == 6, "keyword arguments must be passed through"
def test_raises_after_limit():
"""call n+1 raises RuntimeError"""
@call_limit(1)
def ping():
return 'pong'
ping()
try:
ping()
except RuntimeError:
return
assert False, "the second call should raise RuntimeError"
def test_original_not_called():
"""the original function is not run once the limit is reached"""
calls = []
@call_limit(1)
def record():
calls.append(1)
record()
try:
record()
except RuntimeError:
pass
assert len(calls) == 1, f"original ran {len(calls)} times"
def test_independent_counts():
"""each decorated function counts separately"""
limit = call_limit(1)
f = limit(lambda: 'f')
g = limit(lambda: 'g')
assert f() == 'f' and g() == 'g', "f and g should each get one call"
def test_metadata():
"""wraps preserves name and docstring"""
@call_limit(3)
def greet():
"""Say hello."""
assert greet.__name__ == 'greet', f"got {greet.__name__!r}"
assert greet.__doc__ == 'Say hello.'
Hints (3)
- Three layers.
call_limit(n)returnsdecorator,decorator(fn)returnsinner. - Put the counter inside
decorator(not insidecall_limit), so every decorated function gets its own count. - Check the count before calling
fn, and usenonlocalto update it.
Show a solution
from functools import wraps
def call_limit(n):
def decorator(fn):
count = 0
@wraps(fn)
def inner(*args, **kwargs):
nonlocal count
if count >= n:
raise RuntimeError(f'{fn.__name__} can only be called {n} times')
count += 1
return fn(*args, **kwargs)
return inner
return decoratorExercise 3: A memoizer that understands keyword arguments ✓ Passed
Write a decorator memoize that caches results for both positional and keyword arguments. Calls with the same arguments must run the original function only once.
Requirements:
- expose the cache dictionary as an attribute cache on the decorated function, - treat f(1, b=2) and f(1, b=2) as the same call, and f(a=1, b=2) and f(b=2, a=1) as the same call too (keyword order doesn't matter), - use functools.wraps.
Tip: positional args are a tuple; for the keywords, build something hashable whose value doesn't depend on order, e.g. tuple(sorted(kwargs.items())).
from functools import wraps
def memoize(fn):
cache = {}
@wraps(fn)
def inner(*args, **kwargs):
return fn(*args, **kwargs)
inner.cache = cache
return inner
def test_caches_positional():
"""repeated positional calls run once"""
runs = []
@memoize
def square(x):
runs.append(x)
return x * x
assert square(4) == 16 and square(4) == 16
assert runs == [4], f"square ran for {runs}"
def test_caches_keywords_any_order():
"""keyword order doesn't create new cache entries"""
runs = []
@memoize
def power(base, exp):
runs.append((base, exp))
return base ** exp
assert power(base=2, exp=10) == 1024
assert power(exp=10, base=2) == 1024
assert len(runs) == 1, f"ran {len(runs)} times"
def test_different_args():
"""different arguments are cached separately"""
@memoize
def add(a, b=0):
return a + b
assert add(1, b=2) == 3
assert add(1, b=5) == 6
assert add(1) == 1
assert len(add.cache) == 3, f"cache has {len(add.cache)} entries"
def test_recursion_uses_cache():
"""recursive calls go through the cache"""
runs = []
@memoize
def fib(n):
runs.append(n)
return 1 if n < 3 else fib(n - 1) + fib(n - 2)
assert fib(20) == 6765
assert len(runs) == 20, f"fib's body ran {len(runs)} times, expected 20"
assert len(fib.cache) == 20
def test_metadata():
"""wraps keeps the name"""
@memoize
def thing():
pass
assert thing.__name__ == 'thing'
Hints (3)
- Build one key from both parts:
key = (args, tuple(sorted(kwargs.items()))). - Look the key up in
cachebefore callingfn; store the result after. - Decorating the recursive function means the recursive calls (which look up the global name) also use the cache.
Show a solution
from functools import wraps
def memoize(fn):
cache = {}
@wraps(fn)
def inner(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = fn(*args, **kwargs)
return cache[key]
inner.cache = cache
return innerExercise 4: A tiny JSON encoder with singledispatch ✓ Passed
Using functools.singledispatch, write to_json(value) that returns a JSON string:
- None → null; True/False → true/false - int and float → their repr, e.g. 3 → 3, 2.5 → 2.5 - str → wrapped in double quotes (you may ignore escaping) - list and tuple → [...] with items encoded recursively, separated by , - dict → {...} with "key": value pairs separated by , (keys are strings; encode values recursively) - anything else → raise TypeError
Careful: bool is a subclass of int.
from functools import singledispatch
@singledispatch
def to_json(value):
raise TypeError(f'cannot encode {type(value).__name__}')
@to_json.register(int)
def _(value):
return repr(value)
def test_scalars():
"""numbers, strings and None"""
assert to_json(3) == '3'
assert to_json(2.5) == '2.5'
assert to_json('hi') == '"hi"'
assert to_json(None) == 'null', f"got {to_json(None)!r}"
def test_bools():
"""bools are true/false, not 1/0"""
assert to_json(True) == 'true', f"got {to_json(True)!r}"
assert to_json(False) == 'false'
def test_sequences():
"""lists and tuples become arrays, recursively"""
assert to_json([1, 'a', None]) == '[1, "a", null]'
assert to_json((True, [2.0])) == '[true, [2.0]]'
def test_dict():
"""dicts become objects"""
assert to_json({'a': 1, 'b': [False]}) == '{"a": 1, "b": [false]}'
def test_unsupported():
"""other types raise TypeError"""
try:
to_json({1, 2})
except TypeError:
return
assert False, "a set should raise TypeError"
Hints (3)
- Register
boolseparately.singledispatchpicks the most specific type, so it wins overintforTrueandFalse. None's type istype(None), and you can register it like any other type.- The list and dict implementations call
to_jsonon their items, so nested values are dispatched again.
Show a solution
from functools import singledispatch
@singledispatch
def to_json(value):
raise TypeError(f'cannot encode {type(value).__name__}')
@to_json.register(type(None))
def _(value):
return 'null'
@to_json.register(bool)
def _(value):
return 'true' if value else 'false'
@to_json.register(int)
@to_json.register(float)
def _(value):
return repr(value)
@to_json.register(str)
def _(value):
return f'"{value}"'
@to_json.register(list)
@to_json.register(tuple)
def _(value):
return '[' + ', '.join(to_json(v) for v in value) + ']'
@to_json.register(dict)
def _(value):
pairs = (f'{to_json(k)}: {to_json(v)}' for k, v in value.items())
return '{' + ', '.join(pairs) + '}'