On this page
  1. Decorators and Closures
  2. Contents
  3. Closures & Free Variables
  4. Function Decorators & @functools.wraps
  5. Parameterized & Class Decorators
  6. Built-in & Stdlib Decorators (functools)

Decorators and Closures

Prev: Iterators and Generators | Up: Advanced Python Internals | Next: Concurrency and Parallelism
Rel: python decorators, python metaprogramming, functools, property
Ref: docs.python.org — functools
Tags: #public #python3 #tutorials #internals #decorators #closures


Contents


Closures & Free Variables

A closure is a nested function that captures references to variables from its enclosing scope inside cell objects (fn.__closure__), even after the enclosing function has returned.

def make_multiplier(factor: int):
    def multiply(value: int) -> int:
        return value * factor
    return multiply

double = make_multiplier(2)
print(double(21))  # 42
print([cell.cell_contents for cell in double.__closure__])  # [2]

Function Decorators & @functools.wraps

@decorator is syntactic sugar for func = decorator(func). Always apply [[stdlib_module/functools|@functools.wraps(func)]] to the wrapper so __name__, __doc__, __qualname__, and __wrapped__ are preserved.

from functools import wraps
import time

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

@timed
def compute_sum(n: int) -> int:
    """Sum integers from 0 to n - 1."""
    return sum(range(n))

assert compute_sum.__name__ == "compute_sum"
print(compute_sum(10_000))

Parameterized & Class Decorators

A parameterized decorator is a decorator factory (an outer function returning the actual decorator). A class decorator takes a class object, augments or wraps it, and returns a class.

from functools import wraps

def retry(attempts: int = 3):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            last_exc = None
            for _ in range(attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as exc:
                    last_exc = exc
            raise last_exc
        return wrapper
    return decorator

def register_in(registry: dict):
    def decorator(cls):
        registry[cls.__name__] = cls
        return cls
    return decorator

PLUGINS: dict[str, type] = {}

@register_in(PLUGINS)
class CsvExporter:
    pass

print(PLUGINS)  # {'CsvExporter': <class '...CsvExporter'>}

Built-in & Stdlib Decorators (functools)

from functools import cache, singledispatch

@cache
def fib(n: int) -> int:
    return n if n < 2 else fib(n - 1) + fib(n - 2)

@singledispatch
def serialize(value) -> str:
    return str(value)

@serialize.register
def _(value: list) -> str:
    return "[" + ", ".join(serialize(v) for v in value) + "]"

print(fib(30), serialize([1, 2, 3]))

Linked from

Related notes