Sub topic 10
Building functions with functions
A function factory is a function that returns another function. This chapter shows how to write one, why it works, and when it is useful. It assumes you know how to define functions with def, how lambdas work, and how closures capture variables.
The basic pattern
Python functions are values, so a function can build a new function and return it. The returned function is a closure. It keeps the variables it used from the call that created it.
def make_multiplier(factor):
return lambda x: x * factor
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15Each call to make_multiplier runs the function body again. It creates a new local scope with its own factor, and the returned lambda holds on to that scope. double and triple do not share state.
print(double.__closure__[0].cell_contents) # 2
print(triple.__closure__[0].cell_contents) # 3The __closure__ attribute is useful for debugging. You rarely need it in real code.
Using def inside the factory
A lambda is limited to one expression. When the returned function needs statements, define it with def inside the factory and return it by name.
def make_range_checker(low, high):
def check(value):
if value < low or value > high:
raise ValueError(f"{value} not in [{low}, {high}]")
return value
return check
check_percent = make_range_checker(0, 100)
print(check_percent(42)) # 42The inner function has a name, so it appears in tracebacks. That is an advantage over a lambda.
Factories that produce key functions
Factories pair well with sorted, min and max. Suppose you sort records by different fields:
def by_field(name):
return lambda record: record[name]
people = [
{"name": "Ana", "age": 31},
{"name": "Bo", "age": 25},
{"name": "Cy", "age": 40},
]
print([p["name"] for p in sorted(people, key=by_field("age"))])
# ['Bo', 'Ana', 'Cy']
print([p["name"] for p in sorted(people, key=by_field("name"), reverse=True)])
# ['Cy', 'Bo', 'Ana']by_field("age") is evaluated once, before sorting starts. It returns the function that sorted then calls on every item.
Factories avoid the late-binding bug
The previous chapter showed that lambdas created in a loop all see the final value of the loop variable. A factory fixes this without a default argument, because each call has its own scope.
def make_getter(i):
return lambda: i
getters = [make_getter(i) for i in range(3)]
print([g() for g in getters]) # [0, 1, 2]Here i inside the lambda refers to the factory's parameter, not the loop variable. Each call creates a new parameter that never changes.
Changing captured state with nonlocal
A closure can read captured variables freely. To rebind one, declare it nonlocal in the inner function.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter()) # 1 2 3Without nonlocal, count += 1 would raise UnboundLocalError. Python would treat count as a local variable of increment.
Common errors
- Forgetting to call the factory.
sorted(people, key=by_field)passes the factory itself as the key. It fails with aTypeError, becauseby_fieldreceives a record where it expects a field name. Writeby_field("age"). - Returning a call instead of a function.
return check(value)returns a result. Usereturn checkto return the function. - Capturing a mutable object. Closures capture variables, not copies. If the captured value is a list that you change later, the closure sees the change.
Where this leads
Two later patterns build on the same idea. functools.partial fixes arguments without writing a factory by hand. A decorator is a factory-like function that takes a function and returns a wrapped version of it.
Exercise
Write a function make_prefixer(prefix) that returns a function. The returned function takes a string and returns it with prefix added to the front. What does [make_prefixer("id-")(s) for s in ["a", "b"]] produce?
Show answer
One possible definition is def make_prefixer(prefix): return lambda s: prefix + s. The expression produces ['id-a', 'id-b']. Each call to make_prefixer("id-") creates a closure that remembers prefix.
Exercise
Why does [make_getter(i) for i in range(3)] give distinct results when [lambda: i for i in range(3)] does not?
Show answer
In the factory version, each lambda captures the i parameter of its own make_getter call, so each has a separate variable with a fixed value. In the plain version, all lambdas share the single loop variable i. They read it when called, after the loop has finished and i is 2.