Skip to content
devtoolbox.cc

Python · Chapter 8 of 21

Python lambdas, scope, closures and decorators explained

15 min study · Examples checked with Python 3.14 and 3.15 ·

In Python, a function is an object like any other. You can store it in a variable or a list, pass it to another function, and return it from a function. That one fact explains sort keys, callbacks, closures, decorators and the way web frameworks register request handlers. This chapter goes through them in that order, with the scope rules that make closures work.

Functions are values

def tidy(title: str) -> str:
    return " ".join(title.split()).title()

def apply_to_all(items, transform):
    return [transform(item) for item in items]

titles = ["  python   basics", "django MODELS "]
print(apply_to_all(titles, tidy))   # ['Python Basics', 'Django Models']
print(apply_to_all(titles, len))    # [17, 14]

Writing tidy without parentheses refers to the function; tidy(...) calls it. Passing the function lets the receiver decide when, and how often, to call it. A function that takes or returns other functions is called a higher-order function. sorted(..., key=...), max(..., key=...), map and filter are built-in examples.

lambda, map, filter and partial

A lambda is a function written as a single expression, without a name. It is meant for short throwaway functions, typically sort keys:

from functools import partial

courses = [("Python", 21), ("Django", 8), ("FastAPI", 6)]
print(sorted(courses, key=lambda c: c[1]))   # [('FastAPI', 6), ('Django', 8), ('Python', 21)]
print(max(courses, key=lambda c: c[1])[0])   # Python

print(list(map(str.upper, ["a", "b"])))          # ['A', 'B']
print(list(filter(lambda n: n % 2, range(6))))   # [1, 3, 5]

round_2 = partial(round, ndigits=2)
print(round_2(3.14159))                          # 3.14

map applies a function to every item and filter keeps the items for which a function returns something truthy. Both return lazy iterators, so wrap them in list to see the results. In most Python code a comprehension says the same thing more readably: [s.upper() for s in items]. functools.partial fixes some arguments of an existing function and returns a new callable, which is often clearer than a lambda that only passes arguments through.

If a lambda grows past one short expression, give it a name with def. Named functions appear in tracebacks by name and can have docstrings.

How Python finds a name

When code uses a name, Python looks in four places in order, often abbreviated LEGB: the Local scope of the current function, any Enclosing functions, the Global scope of the module, and the Built-ins. The first match wins.

total = 0
def add_bad(n):
    total += n          # assignment makes total local to add_bad
    return total

try:
    add_bad(5)
except UnboundLocalError as error:
    print(type(error).__name__)  # UnboundLocalError

A local name hides a global one with the same name, and the example shows the rule that confuses people: if a function assigns to a name anywhere in its body, that name is local throughout the whole function. total += n therefore tries to read a local total that has no value yet. The fix is usually to pass the value in and return the result. global total would make the assignment target the module variable, and nonlocal does the same for an enclosing function, but shared mutable state makes code harder to test, so use them sparingly. Changing an object (for example items.append(n)) is not an assignment to the name, and needs neither keyword.

Closures keep their surroundings

A function defined inside another function can use the outer function’s variables, even after the outer call has returned. The inner function together with those remembered variables is a closure.

def make_discount(rate: float):
    def apply(price: float) -> float:
        return round(price * (1 - rate), 2)
    return apply

student = make_discount(0.2)
staff = make_discount(0.5)
print(student(50), staff(50))   # 40.0 25.0

Each call of make_discount creates a separate closure with its own rate. A closure can also change its remembered state, such as a counter that increases on every call; that needs nonlocal count inside the inner function, because count += 1 is an assignment.

Closures look a variable up when they run, not when they are created. Functions made in a loop therefore all see the loop variable’s final value:

late = [lambda: n for n in range(3)]
print([f() for f in late])     # [2, 2, 2]
early = [lambda n=n: n for n in range(3)]
print([f() for f in early])    # [0, 1, 2]

A default argument is evaluated when each lambda is defined, so it captures the current value. A factory function like make_discount is the clearer fix when the function does more than return a number.

Decorators wrap functions

A decorator is a function that takes a function and returns a replacement. The @ syntax applies it at definition time: @timed above def build_report means build_report = timed(build_report).

from functools import wraps
from time import perf_counter

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

@timed
def sum_squares(limit: int) -> int:
    """Add the squares of 0..limit-1."""
    return sum(n * n for n in range(limit))

print(sum_squares(1000))                  # 332833500 (after the timing line)
print(sum_squares.__name__, sum_squares.__doc__)
# sum_squares Add the squares of 0..limit-1.

The wrapper accepts any arguments with *args, **kwargs, forwards them, and returns the original result. Putting the timing in finally means it is printed even when the wrapped function raises. functools.wraps copies the original name, docstring and other metadata onto the wrapper; without it, every decorated function would be called wrapper in tracebacks and documentation.

This wrapper only suits ordinary functions. For an async def function, the wrapper itself must be async def and must await the call, otherwise it would time the creation of a coroutine rather than the work (chapter 21).

Decorators with arguments, and ones you already have

A decorator that takes options is a function that returns a decorator, which gives three levels of nesting:

from functools import cache, wraps

def repeat(times: int):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return [func(*args, **kwargs) for _ in range(times)]
        return wrapper
    return decorator

@repeat(times=2)
def greet(name: str) -> str:
    return f"Hi, {name}"

print(greet("Ada"))  # ['Hi, Ada', 'Hi, Ada']

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

print(fib(90))       # 2880067194370816120

@repeat(times=2) first calls repeat(2), which returns the real decorator; a retry decorator for flaky network calls has exactly this shape. The standard library includes several useful decorators: functools.cache and lru_cache remember results for arguments already seen (here turning an exponential recursion into a fast one), property, staticmethod and classmethod change how methods work (chapter 11), and contextlib.contextmanager builds context managers (chapter 18). Stacked decorators apply from the bottom up, and the order can matter, for example when caching should happen inside or outside a permission check.

Not every decorator wraps. FastAPI’s @app.get("/lessons") registers the function as a route handler and returns it unchanged; Django and pytest use registration decorators too. The syntax is the same; the purpose differs.

Practice

Write make_prefixer(prefix) that returns a function adding prefix to a string. Then write a decorator logged that prints the wrapped function’s name and arguments before each call, returns the original result, and keeps the original __name__.

Answer check: make_prefixer("Learn: ")("Python") returns "Learn: Python". Decorate a small add(a, b); add(2, 3) should print a line such as add (2, 3) {} and return 5, and add.__name__ should still be "add" thanks to @wraps. Make the wrapped function raise and check the exception still reaches the caller.

Summary

Functions are values: pass them, store them, return them. Prefer comprehensions to map/filter and named functions to long lambdas. Names resolve Local, Enclosing, Global, Built-in, and an assignment makes a name local to the whole function. Closures remember variables by reference, and decorators replace or register a function at definition time; always use functools.wraps.

All Python chapters