Sub topic 10
Building functions with functions
This chapter assumes you can write a def function, that you know lambdas and closures from the earlier chapters, and that you are comfortable with *args. It covers function factories: functions whose job is to build and return other functions. It also covers when to use one and which mistakes to avoid.
What a function factory is
A function factory is a function that returns a function. The returned function is configured by the arguments you gave the factory. Because functions are ordinary values in Python, a return statement can hand one back like any other object.
The smallest example uses a lambda:
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15make_multiplier runs once per call. Each run creates a fresh local variable factor and a new lambda that uses it. When make_multiplier returns, its local scope would normally disappear. The lambda keeps factor alive because it is a closure.
Every call makes an independent function
Calling a factory twice gives two separate function objects. Each has its own captured value. You can inspect this directly:
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
triple = make_multiplier(3)
print(double is triple) # False
print(double.__code__.co_freevars) # ('factor',)
print(double.__closure__[0].cell_contents) # 2
print(triple.__closure__[0].cell_contents) # 3co_freevars lists the names the function uses but does not define itself. __closure__ holds one cell for each of those names. You rarely need these attributes in real code. They are useful for debugging, and they show that the captured value belongs to the function object and not to the factory.
Choosing between a lambda and a def inside the factory
A lambda is enough when the inner function is one expression. If you need a statement, a docstring, a useful name in tracebacks, or several lines, define the inner function with def and return it by name.
def by_field(name):
def key(row):
return row[name]
return key
rows = [
{"name": "Ada", "age": 36},
{"name": "Linus", "age": 28},
{"name": "Grace", "age": 45},
]
youngest_first = sorted(rows, key=by_field("age"))
print([r["name"] for r in youngest_first]) # ['Linus', 'Ada', 'Grace']by_field("age") builds a key function for sorted. This is the same job operator.itemgetter("age") does, and the standard library version is usually preferable. Writing your own factory makes sense when the key needs extra logic, such as a default for missing fields or case folding.
A named inner function also gives clearer tracebacks. An error inside a lambda is reported in <lambda>. An error inside key is reported in key.
Validating arguments when the factory runs
The factory body runs once, at build time. The inner function runs every time it is called. Put checks on the configuration in the factory body so a mistake fails early, at the place where the function is built:
def in_range(low, high):
if low > high:
raise ValueError("low must not exceed high")
def check(value):
return low <= value <= high
return check
is_percent = in_range(0, 100)
print(list(filter(is_percent, [-5, 0, 50, 100, 101]))) # [0, 50, 100]
try:
in_range(10, 1)
except ValueError as error:
print(error) # low must not exceed highIf the check lived in check, the bad configuration would only surface on the first call, possibly far from the line that caused it. The same idea lets you do expensive setup once, such as compiling a regular expression, and reuse the result on every call.
Factories that keep changing state
A closure can read the captured variable freely. To rebind it, you must declare it with nonlocal. Without the declaration, assignment makes the name local to the inner function.
def make_counter(start=0):
count = start
def next_value():
nonlocal count
count += 1
return count
return next_value
a = make_counter()
b = make_counter(10)
print(a(), a(), b()) # 1 2 11Each counter has its own count, so a and b do not interfere. If you remove the nonlocal count line, calling a() raises UnboundLocalError. Python sees count += 1, decides count is local to next_value, and finds it unset when it reads it.
Mutating a captured object, such as appending to a list, does not need nonlocal, because you are not rebinding the name. A factory that keeps counters, caches or running totals this way works, but it hides state inside the function. If the state grows beyond one or two values, or other code needs to inspect it, a small class is easier to understand and test.
Building many functions in a loop
Factories solve the late-binding problem from the previous chapter. A lambda written directly in a loop body looks up the loop variable when it is called. A lambda created inside a factory call gets its own scope, so each one sees the value that was passed in:
def make_adder(n):
return lambda x: x + n
adders = [make_adder(n) for n in range(3)]
print([f(10) for f in adders]) # [10, 11, 12]Each call to make_adder has its own n, so the three functions stay distinct. The default-argument trick (lambda x, n=n: x + n) gives the same result. The factory version is clearer when the function is more than a trivial expression, and it cannot be broken by a caller passing an extra argument.
Factories that take functions
A factory can also accept functions as arguments. Then it is both a higher-order function on the way in and a function factory on the way out. A pipeline builder is a typical case:
def pipeline(*funcs):
def run(value):
for func in funcs:
value = func(value)
return value
return run
clean = pipeline(str.strip, str.upper, lambda s: s + "!")
print(clean(" hi ")) # HI!pipeline returns a new function that applies each step from left to right. The steps can be built-in methods, your own functions, lambdas, or the results of other factories such as make_multiplier(2). Decorators, covered in a later chapter, are this same pattern: a function takes a function and returns a function.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Every generated function returns the last loop value | The lambda is written in the loop body and reads the loop variable at call time | Build each function through a factory call, or bind with a default argument |
| `UnboundLocalError` when the inner function updates a captured name | Assignment makes the name local | Declare it `nonlocal` in the inner function |
| Returned function is called with the wrong arguments | The factory was called when you meant to pass it, such as `by_field` instead of `by_field("age")` | Call the factory once, then pass its result |
| `TypeError: 'function' object is not iterable` or similar after a factory call | The factory itself was passed where its result was expected | Check for a missing pair of parentheses |
| Two closures share data unexpectedly | They capture the same mutable object, such as one list created outside the factory | Create the mutable object inside the factory body |
| Tracebacks show only `<lambda>` | Anonymous inner functions have no useful name | Use a named inner `def` |
Factory, partial or class?
Three tools often solve the same problem. The right one depends on what the configured function needs.
- Use a factory when the inner function has custom logic and you want the configuration hidden in the closure.
- Use
functools.partialwhen you only want to fix some arguments of an existing function. The next chapter covers it. - Use a class with
__call__or ordinary methods when the configuration or state must be visible, changed, pickled, or documented as part of an interface.
Closures are not pickled by the standard pickle module, because it cannot store functions defined inside other functions. If you need to send a configured function to another process, as with multiprocessing, prefer partial on a module-level function or a class instance.
Exercise
Write a factory make_prefixer(prefix) that returns a function adding prefix to the front of any string. Use it to build warn = make_prefixer("WARNING: "), then predict what warn("disk full") and warn("low memory") return.
Show answer
def makeprefixer(prefix):
return lambda text: prefix + text
warn = makeprefixer("WARNING: ")
print(warn("disk full")) # WARNING: disk full
print(warn("low memory")) # WARNING: low memory
The factory captures prefix once, and both calls to warn reuse it.
Exercise
This code is meant to print 1, 2, 3 but raises an error on the first call. Explain why and fix it. def maketotal(): total = 0 def addone(): total += 1 return total return addone counter = maketotal() print(counter())
Show answer
The assignment total += 1 makes total a local variable of add_one. It is read before it has a value, so Python raises UnboundLocalError. Declare the name as nonlocal inside add_one:
def maketotal():
total = 0
def addone():
nonlocal total
total += 1
return total
return addone
Now repeated calls to counter() return 1, 2, 3, and each call to `maketotal()` starts its own count.
Exercise
You build checks = [lambda v: v > limit for limit in (10, 20, 30)] and find that all three functions behave the same way. Rewrite the list using a factory so each function uses its own limit.
Show answer
def greaterthan(limit):
return lambda v: v > limit
checks = [greaterthan(limit) for limit in (10, 20, 30)]
print([check(15) for check in checks]) # [True, False, False]
Each greater_than call creates its own scope with its own limit. In the original, all lambdas read the same loop variable after the loop ended, so they all used 30.