Tutorials / Python: Intermediate to Advanced / Closures and decorators

Closures and decorators

15 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

Functions are values

In Python a function is an object, like a number or a list. You can store it in a variable, pass it to another function and return it from one. Decorators are built on that single fact.

def shout(text):
    return text.upper()

action = shout          # no brackets: we are not calling it
print(action("hello"))  # HELLO

Closures

A function defined inside another function can use the outer function's variables, even after the outer function has returned. That combination is a closure.

def make_multiplier(factor):
    def multiply(value):
        return value * factor     # 'factor' is remembered
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))     # 20 30

Each call to make_multiplier creates a separate multiply function with its own remembered factor. If you want the inner function to change an outer variable, declare it with nonlocal, otherwise Python treats the assignment as a new local variable.

A first decorator

A decorator is a function that takes a function and returns a new function, usually one that wraps the original with extra behaviour. Say you want to know how long some slow functions take:

import functools
import time


def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.4f}s")
    return wrapper


@timed
def build_report(rows):
    """Sum a pretend report."""
    return sum(i * i for i in range(rows))


print(build_report(1_000_000))
print(build_report.__name__)
print(build_report.__doc__)

The output shows the timing line (the exact time depends on your machine), then the result, the name build_report and the docstring.

What the @ means

Writing @timed above the function is just a shorter way to write build_report = timed(build_report). From then on, the name build_report refers to wrapper. The wrapper accepts any arguments with *args, **kwargs, passes them on to the real function, and returns whatever it returns.

The try/finally makes sure the timing line prints even if the function raises an exception. And @functools.wraps(func) copies the name and docstring of the original function onto the wrapper. If you forget it, every decorated function is named wrapper, which makes tracebacks and debugging confusing. I treat it as mandatory.

Decorators with arguments

Suppose you want @retry(times=3). Now there are three layers: one that takes the settings, one that takes the function, and the wrapper.

import functools
import time


def retry(times=3, delay=0.5, exceptions=(Exception,)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as error:
                    if attempt == times:
                        raise
                    print(f"Attempt {attempt} failed: {error}. Retrying...")
                    time.sleep(delay)
        return wrapper
    return decorator


@retry(times=3, delay=0.1, exceptions=(ConnectionError,))
def fetch_rate():
    ...

retry(times=3, ...) runs first and returns decorator. Then @ applies decorator to the function. When the last attempt fails, the bare raise re-raises the original exception so the caller sees what really went wrong. Catching only the exceptions that make sense to retry is important: retrying a ValueError from bad input only wastes time.

Built-in decorators worth knowing

  • functools.lru_cache remembers results of a function for given arguments. Great for pure, expensive calls.
  • functools.cache is the unbounded version.
  • @staticmethod, @classmethod and @property change how methods in a class behave. We use them in the OOP lessons.
from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(80))    # instant. Without the cache this would take ages.

Common mistakes

  • Forgetting to return the result. If the wrapper calls func(...) without return, the decorated function always gives None.
  • Forgetting functools.wraps. Names and docstrings are lost.
  • Using @decorator when it needs brackets. @retry without brackets passes the function as times and breaks in a confusing way. If your decorator takes settings, always write @retry().
  • Caching functions with side effects or mutable arguments. lru_cache needs hashable arguments, so lists fail, and cached results hide changes in the outside world.
  • Hiding too much. A decorator that changes what a function does in surprising ways makes code hard to follow. Keep them for cross-cutting concerns such as timing, logging, retries and access checks.

Try it yourself

Write a decorator log_calls that prints the function name, its arguments and its return value every time the function runs. Apply it to a function add(a, b). Then write require_positive that raises ValueError if any numeric argument is zero or negative. Stack both decorators on one function and work out in which order they run.

python
import functools
import time


def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.4f}s")
    return wrapper


@timed
def build_report(rows):
    """Sum a pretend report."""
    return sum(i * i for i in range(rows))


print(build_report(1_000_000))
print(build_report.__name__)
print(build_report.__doc__)

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account