Python Functions: Closures, Factories, and partial
Functions in Python are objects, and once you accept that, a group of techniques that used to look like tricks become ordinary engineering: a function can carry state, be built by another function, be wrapped with extra behaviour, and be partially applied so it fits a callback signature. What separates working code from subtly broken code in this area is timing â when a captured variable is read, what happens to a default argument, and what the recursion limit does to a tree walk. This lesson covers closures and late binding, factories, decorator mechanics with functools.wraps, partial, and the shape recursion should take when it is the clearest option.
What You'll Learn
- 1Explain closure capture and the late-binding surprise it causes
- 2Build function factories and compare them with classes and partial
- 3Wrap functions with decorators while preserving metadata
- 4Choose recursion depth, memoisation, and iteration deliberately
Closures and the moment of capture
A closure is a function together with the names it references from the enclosing scope, captured at definition rather than copied. Each call to the outer function creates a fresh enclosing scope, so two closures built from the same factory hold independent state â which is what makes them useful as lightweight objects. To modify a captured variable from inside the inner function you need nonlocal; without it, assignment creates a local name and Python raises UnboundLocalError at run time.
The trap that catches everyone is late binding. Closures look up free variables when the inner function is called, not when it is defined, so a loop that builds a list of functions ending in the same variable produces several handles to one value. The standard fixes are to bind the current value as a default argument or to wrap the body in an extra function that receives it as a parameter. Both make the capture point explicit, and the default-argument form is the one you will see most often in callbacks and event handlers.
def make_counter(start=0):
count = start
def increment(step=1):
nonlocal count
count += step
return count
return increment
tally = make_counter()
print(tally(), tally(5), tally()) # 1 6 7
other = make_counter(100)
print(other()) # 101 â independent state
# late binding: every function sees the final value
late = [lambda: i for i in range(3)]
print([f() for f in late]) # [2, 2, 2]
# early binding: capture i at definition time
early = [lambda i=i: i for i in range(3)]
print([f() for f in early]) # [0, 1, 2]
Closures are also how Python implements callbacks without ceremony: the inner function keeps its environment alive as long as something references it, and garbage collection reclaims both together. That is why a closure handed to a long-lived registry keeps the enclosing frame's locals alive â a memory consideration worth remembering when capturing large objects.
Factories: configuration without a class
A factory is any function that returns a function. It exists to turn configuration that would otherwise be passed on every call into part of the function itself. Validation rules, arithmetic operators, formatting styles, and SQL fragments all fit this shape: the configuration stays fixed while the payload varies. When the same configuration would drive several related functions, a factory returning a small object or a dictionary of closures is the natural midpoint between a bare function and a full class.
Factories beat lambda chains for anything with more than one line, because the body can hold comments, validation, and multiple statements. They also beat class-based alternatives when there is behaviour but no meaningful identity or inheritance â a class whose only job is to hold one captured value and expose one method is usually clearer as a closure. The moment you need several methods, shared mutable state, or isinstance checks, promote it to a class.
def create_validator(low, high, label="value"):
def validate(number):
if not isinstance(number, (int, float)):
raise TypeError(f"{label} must be numeric, got {type(number).__name__}")
if not (low <= number <= high):
raise ValueError(f"{label} must be between {low} and {high}")
return number
return validate
age = create_validator(0, 150, "age")
percent = create_validator(0, 100, "percent")
print(age(42)) # 42
print(percent(99.5)) # 99.5
for check, bad in ((age, -1), (percent, 140)):
try:
check(bad)
except ValueError as exc:
print("rejected:", exc)
def make_adder(n):
return lambda value: value + n
add_seven = make_adder(7)
print(add_seven(5)) # 12
Notice that each validator closes over its own low, high, and label, so the three functions never interfere. The error messages are built once per factory call rather than on every validation, which is a small but real saving when a validator runs inside a hot loop.
Decorators without losing the original function
A decorator is a callable that takes a function and returns a replacement, applied with the @ syntax. The replacement is usually a wrapper that runs something before and after delegating to the original, and the pattern generalises cleanly to timing, logging, retries, access control, and caching. Two mechanical details decide whether the result is professional or a maintenance problem.
The first is metadata: without functools.wraps, the wrapper reports its own name, docstring, and signature, so introspection, test names, and framework auto-documentation all break. The second is argument forwarding: the wrapper must accept *args and **kwargs and pass them through unchanged, otherwise decorated functions with different signatures fail as soon as they are wrapped. Decorators that themselves take arguments add a third layer, which is why the shape nests as decorator, factory, wrapper.
import functools
import time
def traced(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:.6f}s")
return wrapper
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@traced
@repeat(3)
def collate(rows):
return sum(rows)
print(collate([1, 2, 3])) # 6, printed after three inner runs
print(collate.__name__) # collate â metadata preserved
Stacking order matters: decorators apply bottom up, so @traced wraps the result of @repeat(3), meaning timing covers all three repetitions rather than each one. Reading a stack of four decorators as "outermost runs first, innermost runs closest to the function" removes most of the confusion.
partial and friends
functools.partial binds arguments to a callable, producing a new callable with a shorter signature. Its value shows up when a callback interface demands a fixed shape â a thread pool wants a zero-argument callable, a map-style call wants one argument â and the function you have takes two. Partial also expresses intent better than a lambda one-liner: partial(scale, 2.0) reads as configuration, while lambda x: scale(2.0, x) reads as code the reader must parse.
Beyond partial, the standard library offers functools.partialmethod for classes, functools.lru_cache for memoisation, and operator.itemgetter and attrgetter for the extremely common case of extracting a key in a sort or groupby. Combining a key extractor with a sort is both faster and clearer than a lambda, because the extraction runs in C.
from functools import partial, lru_cache
from operator import itemgetter
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5), cube(5)) # 25 125
records = [{"id": 3, "name": "c"}, {"id": 1, "name": "a"}, {"id": 2, "name": "b"}]
print([r["name"] for r in sorted(records, key=itemgetter("id"))]) # ['a', 'b', 'c']
@lru_cache(maxsize=1024)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60), fib.cache_info().hits) # 1548008755920 with hits on repeats
The cached fib also shows the limits of partial thinking: memoisation turns an exponential recursion into a linear one, but only when the arguments are hashable and the function is pure. A partial bound to a mutable default or an unpicklable object will fail later, usually at the point where it crosses a process boundary.
Recursion, base cases, and the depth limit
Recursion earns its place when the problem is genuinely self-similar: tree traversal, directory walking, nested structure flattening, and divide-and-conquer algorithms. Python sets a recursion limit, reported by sys.getrecursionlimit, that defaults around a thousand frames. Raising it is possible but only postpones the real constraint, which is C stack space: on deep recursion the interpreter raises RecursionError, and on some platforms the failure is a hard crash rather than a catchable exception.
Two discipline rules keep recursive code healthy. Every recursive path must move toward the base case; a missing progress step loops until the limit is hit. And overlapping subproblems should be memoised, either explicitly with a dictionary or with lru_cache, because naive Fibonacci-style recursion re-does exponential work. When neither condition holds â deep inputs or repeated subproblems â an explicit stack or bottom-up table is the correct implementation, not a fallback.
import sys
import functools
@functools.lru_cache(maxsize=None)
def count_paths(grid_size):
rows, cols = grid_size
if rows == 0 or cols == 0:
return 1
return count_paths((rows - 1, cols)) + count_paths((rows, cols - 1))
print(count_paths((6, 6))) # 924 paths, memoised
print(sys.getrecursionlimit()) # typically 1000
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]
The flatten generator is recursive in structure but iterative in consumption: yield from delegates without building intermediate lists, so memory stays flat even for deeply nested input. That combination â recursion for shape, generators for output â is usually the most elegant solution Python offers for tree-shaped data.
Choosing between a closure, a class, and a partial
All three bundle behaviour with configuration, and picking one is mostly about how much structure the problem demands. A closure is right when there is one piece of captured configuration and one function. A class is right when there is identity, several methods, inheritance, or state that must survive and be inspected. A partial is right when you already have a perfectly good function and only need to fix some of its arguments.
| Need | Best tool | Why |
|---|---|---|
| One captured value, one behaviour | Closure | Minimal ceremony, automatic scoping |
| Several methods on shared state | Class | Identity, self, and isinstance |
| Fix leading arguments of an existing callable | functools.partial | Delegates directly, no wrapper frame |
| Metadata must survive wrapping | Decorator with functools.wraps | Preserves name, doc, and signature |
| Key extraction for sort or group | itemgetter / attrgetter | Runs in C, reads clearly |
| Repeat calls with the same arguments | lru_cache | Turns recomputation into lookup |
A practical tie-breaker: if you find yourself writing self in a class that has exactly one method and one attribute, a closure would have said the same thing in a third of the lines. Conversely, if a closure grows a second and third inner function sharing the same state, that shared state is a signal that a class with fields would communicate the design better.
Common Mistakes
Capturing a loop variable in a lambda and getting the final value every time
Fix: Bind it as a default argument (lambda i=i: ...) or extract a factory that creates the function per iteration
Forgetting nonlocal before assigning to a captured variable
Fix: Declare nonlocal explicitly, or return a new value instead of mutating the enclosing scope
Writing a decorator wrapper without functools.wraps
Fix: Apply @functools.wraps(func) so __name__, __doc__, and the signature survive
Using a mutable object as a default argument value
Fix: Default to None and create the list or dict inside the function so each call gets a fresh one
Recursing over input that can exceed the recursion limit
Fix: Convert to an explicit stack or an iterative generator, and only raise the limit with a measured reason
Best Practices
- Bind captured values eagerly when a closure is created inside a loop
- Prefer itemgetter and attrgetter over lambdas for sort and groupby keys
- Forward *args and **kwargs through wrappers and keep signatures honest with wraps
- Memoise pure recursive functions whose subproblems repeat
- Promote a closure to a class as soon as it needs a second method or shared mutable state
Interview Questions
Q1: What is late binding in a closure and how do you avoid its bug?
Free variables are resolved when the inner function is called, so functions created in a loop all see the final value. Fix it by capturing the current value as a default argument or by passing it explicitly through a factory.
Q2: Why does functools.wraps matter in a decorator?
Without it the wrapper hides the original name, docstring, and signature, which breaks introspection, help output, test reporting, and frameworks that inspect signatures. wraps copies those attributes from the wrapped function.
Q3: When is recursion the wrong tool in Python?
When input depth can approach the recursion limit, when subproblems overlap and are not memoised, or when the stack frames cost more than an iterative solution. Python frames are heavy, so iteration often wins on both safety and speed.
Key Takeaways
- Closures capture names, not values â control the timing with defaults or factories
- Factories replace small configuration classes when one behaviour is all that is needed
- Decorators need wraps and full argument forwarding to stay transparent
- partial binds arguments instead of wrapping behaviour, and itemgetter beats lambdas in hot sorts
- Recursion suits tree-shaped problems but needs progress, memoisation, and respect for the depth limit