Code

Caches, Registries & Class Decorators

Decorators shine for cross-cutting jobs, things many functions need but that aren't their main purpose:

import functools, time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            ms = (time.perf_counter() - start) * 1000
            print(f"{func.__name__} took {ms:.2f} ms")
    return wrapper
  • Caching: remember results for arguments seen before. The standard library has this built in as @functools.cache and @functools.lru_cache(maxsize=128): but building one teaches a lot.
  • Registries: a decorator can simply record a function somewhere and return it unchanged. Web frameworks use this for routes (@app.get("/home")).
  • Class decorators: the same idea applied to a class. Receive the class, modify or register it, return it. @dataclass is one!

Assignment

  1. memoize(func): finish the wrapper so it returns cache[args] when args was seen before, otherwise calls func, stores the result in cache, and returns it.
  2. command(name): a decorator factory that stores the decorated function in COMMANDS[name] and returns the function unchanged.
  3. with_repr(cls): a class decorator that gives cls a __repr__ showing ClassName(attr=value, ...) built from vars(self), values shown with repr. Return cls.