Programming · intermediate
Pure function
A pure function's result is determined only by its explicit inputs, and evaluating it causes no externally observable side effects. A call can therefore be replaced by its result without changing program behavior in the relevant model.
Why it matters
Pure functions are easier to test, cache, reorder, parallelize, and reason about because hidden state and action ordering do not alter their meaning. Programs still isolate necessary effects at explicit boundaries.
Mental model
How to reason about pure function
Treat the function as a mathematical mapping from input values to an output value. Local implementation details may allocate or mutate unobserved temporary state, but callers observe only the returned result and defined termination or error behavior.
Analogy
A pure function is a reliable formula on a worksheet: the same supplied numbers yield the same answer, and calculating it does not alter the measuring instruments or the room.
Examples
See the boundary, not just the happy path
Worked example · Compute from explicit inputs
def area(width, height):
return width * heightFor ordinary numeric inputs, the result depends only on width and height and the function performs no observable I/O or external mutation.
Worked example · Return transformed immutable data
def normalized(name):
return name.strip().casefold()The Python string operations return values without changing the input string. The function does not consult locale, time, files, or mutable globals.
Useful contrast · Hidden input makes a function impure
def greeting():
return f'Hello at {datetime.now()}'The current clock is an implicit input, so repeated calls with no explicit arguments can return different results. Passing a time value explicitly would make that dependency visible.
Common mistakes
Misconceptions to remove early
Equating pure with no local computation or allocation
Purity concerns observable behavior. A function may allocate temporary values or use unobservable local mutation internally while still presenting a pure mapping.
Calling deterministic logging pure
Even if the returned value is repeatable, writing a log is an observable side effect. Determinism alone is necessary but not sufficient for purity.
Quick check
Can you predict the result?
1. Which change most directly makes a clock-dependent calculation easier to keep pure?
- • Pass the relevant time as an explicit argument.
- • Read the system clock twice and average it.
- • Store the clock in another mutable global.
2. Why is a function that returns the same value but writes a file not pure?
Keep building