Functions & Decorators
First-class functions, parameter kinds (positional-only, keyword-only, *args, **kwargs), scope and the LEGB rule, closures and nonlocal, decorators with and without arguments, functools (wraps, cache, partial), and context managers.
Functions in Python are objects: you can store them, pass them, return them and attach attributes to them. Decorators — one of Python's most recognisable features — are just a neat syntax for functions that wrap other functions.
Parameter kinds
def f(pos_only, /, normal, *, kw_only):
...
f(1, 2, kw_only=3) # ✓
f(1, normal=2, kw_only=3) # ✓
f(pos_only=1, ...) # ✗ positional-only
f(1, 2, 3) # ✗ kw_only must be named
def log(message, *args, level="INFO", **kwargs):
# args: tuple of extra positionals; kwargs: dict of extra keywords
print(level, message % args, kwargs)
log("user %s logged in from %s", "ada", "10.0.0.1", level="DEBUG", request_id="r1")
# Unpacking at the call site
coords = (3, 4)
opts = {"sep": ", ", "end": "\n"}
print(*coords, **opts)Order in a signature: positional-only, /, normal, *args (or bare *), keyword-only, **kwargs.
Scope: the LEGB rule
Name lookup checks four scopes in order: Local → Enclosing functions → Global (module) → Built-in.
x = "global"
def outer():
x = "enclosing"
def inner():
print(x) # "enclosing" — found in the enclosing scope
inner()
counter = 0
def increment():
global counter # needed to REBIND a module-level name
counter += 1
def make_counter():
count = 0
def inc():
nonlocal count # needed to rebind a name from the enclosing function
count += 1
return count
return incAssigning to a name anywhere in a function makes it local for the whole function — hence UnboundLocalError if you read it before assigning without global/nonlocal.
Python's closures capture variables, not values (late binding):
fns = [lambda: i for i in range(3)]
[f() for f in fns] # [2, 2, 2]
fns = [lambda i=i: i for i in range(3)] # default arg captures the current value
[f() for f in fns] # [0, 1, 2]Higher-order functions
def compose(*fns):
def composed(x):
for f in reversed(fns):
x = f(x)
return x
return composed
slugify = compose(lambda s: s.replace(" ", "-"), str.lower, str.strip)
slugify(" Hello World ") # 'hello-world'
list(map(str.upper, words)); list(filter(None, values)) # comprehensions are usually clearer
from functools import reduce
reduce(lambda acc, x: acc * x, [1, 2, 3, 4], 1) # 24Decorators
A decorator is a callable that takes a function and returns a replacement. @decorator above a def is shorthand for func = decorator(func).
import functools, time
def timed(func):
@functools.wraps(func) # copy __name__, __doc__, etc. to the wrapper
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:.1f} ms")
return wrapper
@timed
def fetch_report(day):
...
# equivalent to: fetch_report = timed(fetch_report)Decorators with arguments
Add one more level: a function that returns a decorator.
def retry(times=3, exceptions=(Exception,), delay=0.1):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == times:
raise
time.sleep(delay * 2 ** (attempt - 1)) # exponential backoff
return wrapper
return decorator
@retry(times=5, exceptions=(ConnectionError,))
def call_api(): ...Stacking and order
@timed
@retry(times=3)
def f(): ...
# f = timed(retry(times=3)(f)) — the decorator nearest the def is applied first;
# at call time, timed's wrapper runs outermostClass-based decorators and decorating classes
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func, self.calls = func, 0
def __call__(self, *args, **kwargs):
self.calls += 1
return self.func(*args, **kwargs)
def register(cls): # class decorators receive the class
REGISTRY[cls.__name__] = cls
return clsReal-world decorators: @app.get("/users") (FastAPI/Flask route registration), @pytest.fixture, @login_required, @dataclass, @property, @staticmethod, @classmethod, @functools.cache.
functools essentials
from functools import cache, lru_cache, partial, wraps, singledispatch, cached_property
@cache # unbounded memoisation (3.9+)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(200) # instant
@lru_cache(maxsize=1024) # bounded, least-recently-used eviction
def load_user(user_id): ...
load_user.cache_info(); load_user.cache_clear()
int_from_binary = partial(int, base=2) # pre-fill arguments
int_from_binary("1010") # 10
class Report:
@cached_property # computed once per instance, then stored
def summary(self): ...Cached functions need hashable arguments, and caching methods with @cache keeps self alive forever (a memory leak) — prefer cached_property or a cache keyed explicitly.
Context managers
The with statement guarantees setup and teardown. Write your own with a class (__enter__/__exit__) or, more simply, a generator:
from contextlib import contextmanager, suppress, ExitStack
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield # the body of the with-block runs here
finally:
print(f"{label}: {time.perf_counter() - start:.3f}s")
with timer("load"):
data = load()
with suppress(FileNotFoundError): # ignore a specific exception
os.remove("tmp.txt")
with ExitStack() as stack: # a dynamic number of context managers
files = [stack.enter_context(open(p)) for p in paths]Lambdas, briefly
lambda args: expression creates a small anonymous function — a single expression, no statements. Good for key= arguments; for anything longer, a named def is clearer and debuggable.
- Functions are first-class objects; parameters can be positional-only (/), keyword-only (*), *args and **kwargs.
- Name lookup follows LEGB; use nonlocal/global to rebind outer names; closures bind late.
- A decorator is a function returning a wrapper; always use functools.wraps.
- Decorators with arguments need an extra outer function; the decorator closest to def applies first.
- functools gives cache, lru_cache, partial, cached_property and singledispatch.
- contextmanager turns a generator into a with-block helper with guaranteed cleanup.
QWrite a decorator that caches a function's results.medium
Create a dict in the decorator's scope. The wrapper builds a key from args and a frozenset of kwargs items, returns the cached value if present, otherwise calls the function, stores and returns the result. Use functools.wraps to preserve metadata. In practice, functools.lru_cache or functools.cache already does this with thread safety and size limits.
QWhat do *args and **kwargs do?easy
In a function definition, *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. At a call site, * unpacks an iterable into positional arguments and ** unpacks a mapping into keyword arguments. Together they let wrappers forward any arguments unchanged.