Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 10

Functions, Closures & Decorators (LEGB scoping, late binding gotcha, production-grade decorators with functools.wraps)

878 words · about 4 min

10.1 LEGB Scoping

x = "global"
def outer():
    x = "enclosing"
    def inner():
        x = "local"
        print(x)          # "local"
    inner()
    print(x)              # "enclosing"
outer()
print(x)                  # "global"

Python resolves names Local → Enclosing → Global → Built-in. global/nonlocal explicitly opt into modifying an outer scope; without them, any assignment inside a function makes that name local for the entire function body — including lines before the assignment, causing UnboundLocalError if read first.

10.2 Closures and the Late Binding Gotcha

# Classic mistake: closures capture variables, not values
functions = [lambda: i for i in range(5)]
print([f() for f in functions])   # [4, 4, 4, 4, 4] — all see the FINAL value of i

# Fix 1: default argument captures the value at definition time
functions = [lambda x, i=i: i for i in range(5)]
print([f() for f in functions])   # [0, 1, 2, 3, 4]

# Fix 2: factory function
def make_func(i): return lambda: i
functions = [make_func(i) for i in range(5)]

This is one of the most common Python interview gotchas: lambdas/closures capture the variable (a cell), not its value at creation time, so by the time the lambdas are called, the loop variable has already reached its final value.

10.3 Production-Grade Decorators

import functools, time, logging

def retry(max_attempts=3, backoff_factor=2):
    """Decorator factory: retry on exception with exponential backoff."""
    def decorator(func):
        @functools.wraps(func)  # Preserves __name__, __doc__, __wrapped__
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    wait = backoff_factor ** attempt
                    logging.warning(f"{func.__name__} attempt {attempt+1} failed: {e}")
                    time.sleep(wait)
            raise last_exception
        return wrapper
    return decorator

@retry(max_attempts=3)
def unreliable_api_call():
    ...

functools.wraps is non-negotiable in production decorators: without it, the wrapped function’s __name__, __doc__, and signature all become the wrapper’s, breaking stack traces, help(), introspection-based frameworks, and anything relying on __wrapped__ to reach the original function.

Decorators with arguments need an extra layer: decorator_with_args(arg1, arg2) is called first (a factory), returning actual_decorator(func), which returns wrapper(*args, **kwargs). Stacking decorators applies bottom-up but executes top-down: @a @b @c def f() means f = a(b(c(f))), so calling f() hits a’s wrapper first, which calls into b’s, which calls into c’s, which finally calls the original.

10.4 functools Toolbox

from functools import lru_cache, partial, singledispatch, total_ordering

@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)

square = partial(pow, exp=2)  # freeze arguments

@singledispatch
def process(data):
    raise TypeError(f"Cannot process {type(data)}")
@process.register(int)
def _(data): return f"int: {data * 2}"

@total_ordering
class Student:
    def __eq__(self, other): return self.grade == other.grade
    def __lt__(self, other): return self.grade < other.grade
    # __le__, __gt__, __ge__ auto-generated

Interview Q&A — Section 10

Q1: What is a closure, and how does Python handle free variable capture?

A: A closure is a function that retains access to variables from its enclosing scope even after that scope has finished executing. Python captures free variables by reference (via cell objects visible in function.__closure__), not by value — so late binding means the closure sees whatever the variable’s value is when the closure is called, not when it was defined. This is precisely what causes the classic “all lambdas in a loop return the same value” bug.

Q2: What does functools.wraps do, and why is skipping it a red flag in code review?

A: It copies __name__, __doc__, __module__, and sets __wrapped__ on the wrapper function, so decorated functions retain their original identity. Without it, every decorated function reports its name as "wrapper" in stack traces and help(), breaking debuggability, documentation generation, and any framework or test tool that introspects function metadata. It’s a near-zero-cost fix, so its absence signals the decorator wasn’t written carefully.

Q3: Explain the UnboundLocalError gotcha with a concrete example.

A: If a variable is assigned anywhere within a function body, Python treats it as local for the entire function — even on lines before the assignment. So def f(): print(count); count = 1 raises UnboundLocalError, not a fallback to a same-named global, because the assignment on the later line makes count local throughout. Fix by either not shadowing the name, or explicitly declaring global count/nonlocal count if mutating an outer scope’s variable is intended.

Q4: Given @decorator_a @decorator_b def f(): ..., what’s the order of execution and why?

A: Decorators are applied bottom-up at definition time — decorator_b wraps f first, then decorator_a wraps that result, i.e. f = decorator_a(decorator_b(f)). But they execute top-down when called — decorator_a’s wrapper runs first, which calls into decorator_b’s wrapper, which finally calls the original f. The mental model: application is inside-out, execution is outside-in.