Python theorytheory 0/50 · 0%
Functions · medium

22. Decorators

Functions that wrap other functions to add behavior.

A decorator is a function that takes a function and returns a (usually wrapped) function, applied with `@decorator` syntax.

python
import functools

def log_call(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        print(f"calling {fn.__name__}")
        return fn(*args, **kwargs)
    return wrapper

@log_call
def mint(amount):
    return amount

mint(5)   # prints "calling mint", returns 5

`functools.wraps` preserves the original function's name and docstring, which matters for debugging and introspection. Decorators are commonly used for logging, timing, caching (`functools.lru_cache`), and access control.

Check your understanding

  1. 1. What does `@log_call` above a function definition do?

  2. 2. What does `functools.wraps` do?

  3. 3. Which stdlib decorator provides memoization?