Configure a function for later

Lesson 12 of 20 · Functional Python: values, behavior, and choices

The run function in the previous lesson can still use first and second after chain returns. It is a closure: a function retaining access to bindings in an enclosing function scope. A reference to a global name alone is not such an enclosing-function capture.

def make_scale(factor):
    def scale(reading):
        return reading * factor
    return scale

double = make_scale(2)
triple = make_scale(3)
print(double(7), triple(7))
14 21

Each call to make_scale creates a separate binding. Reading factor needs no nonlocal. The value of a fixed integer configuration and the later input determine each result; a closure is not necessarily stateful in the sense of changing on every call.

Partial application fixes some arguments of an existing function, producing a callable that accepts the rest. This is useful when a callback needs a particular argument shape.

from functools import partial

def convert(factor, reading):
    return factor * reading

use_double = partial(convert, 2)
print(list(map(use_double, [4, 7])))
[8, 14]

map supplies one reading at a time; partial supplies the earlier positional argument. It returns an iterator, so list consumes it to show the values. Mutable objects supplied to a closure or partial are shared references, not automatic snapshots.

Currying transforms a multi-argument operation into a chain of single-argument functions. Python does not do this automatically:

def scaled_by(factor):
    def apply_to(reading):
        return factor * reading
    return apply_to

print(scaled_by(2)(7))
14

scaled_by(2) returns a function; (7) calls that result. Partial application can fix several arguments at once, whereas strict currying takes one per stage. If all arguments are already available, the ordinary convert(2, 7) may be simpler.

Chapter index