Predictable calculations

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

A pure function returns the same result for the same input values and produces no observable side effects. An effect is an observable action beyond returning the result, such as writing a file, printing, or changing a caller’s list. A function can return a predictable value and still have an effect.

def remaining(capacity, occupied):
    return capacity - occupied

print(remaining(12, 5))
print(remaining(12, 5))
7
7

The calculation receives both inputs explicitly. The two print calls are outside it and display its results. Reading a clock, random generator, or mutable global can introduce a hidden dependency: the same arguments may no longer determine the result.

Local variables, loops, and changes to newly created local data do not by themselves make a function impure if nothing outside can observe those changes. Purity does not ensure correctness, and deterministic exceptions can still be part of a function’s behavior.

Chapter index