Scopes, Closures and Decorators · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What happens when this code runs?
x = 10

def f():
    print(x)
    x = 20

try:
    f()
except Exception as ex:
    print(type(ex).__name__)
2. What does this print?
def outer():
    x = 'a'
    def middle():
        x = 'b'
        def inner():
            nonlocal x
            x = 'c'
        inner()
        return x
    return middle(), x

print(outer())
3. Which statement about nonlocal is correct?
4. What does this print?
funcs = []
for i in range(3):
    funcs.append(lambda: i)

print([f() for f in funcs])
5. What does this print?
def counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    return inc

c1 = counter()
c2 = counter()
c1()
c1()
print(c1(), c2())
6. What does a function's __closure__ attribute contain when the function is a closure?
7. What is the order of the printed lines?
def dec(fn):
    print('decorating')
    def inner():
        print('before')
        return fn()
    return inner

@dec
def f():
    print('calling f')

print('defined')
f()
8. What does this print?
def shout(fn):
    def inner(*args, **kwargs):
        print('calling', fn.__name__)
        fn(*args, **kwargs)
    return inner

@shout
def add(a, b):
    return a + b

print(add(1, 2), add.__name__)
9. What does this print?
def tag(name):
    def decorator(fn):
        def inner():
            return f'<{name}>' + fn() + f'</{name}>'
        return inner
    return decorator

@tag('b')
@tag('i')
def hello():
    return 'hi'

print(hello())
10. Which statement about functools caching decorators is false?
11. What does this print?
from functools import singledispatch

@singledispatch
def kind(x):
    return 'object'

@kind.register(int)
def _(x):
    return 'int'

@kind.register(str)
def _(x):
    return 'str'

print(kind(True), kind(3.5), kind('3'))
12. A class decorator @register_plugin is applied to class Csv: .... What must register_plugin return so that the name Csv still refers to the class?

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

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.

Hints (2)
  1. The starter raises UnboundLocalError. Why does total = total + value make total local to add?
  2. Declare nonlocal total inside add so 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 add

Exercise 2: A decorator factory that limits calls

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.

Hints (3)
  1. Three layers. call_limit(n) returns decorator, decorator(fn) returns inner.
  2. Put the counter inside decorator (not inside call_limit), so every decorated function gets its own count.
  3. Check the count before calling fn, and use nonlocal to 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 decorator

Exercise 3: A memoizer that understands keyword arguments

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())).

Hints (3)
  1. Build one key from both parts: key = (args, tuple(sorted(kwargs.items()))).
  2. Look the key up in cache before calling fn; store the result after.
  3. 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 inner

Exercise 4: A tiny JSON encoder with singledispatch

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.

Hints (3)
  1. Register bool separately. singledispatch picks the most specific type, so it wins over int for True and False.
  2. None's type is type(None), and you can register it like any other type.
  3. The list and dict implementations call to_json on 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) + '}'