Pure Functions
Pure Functions
"Functional programming is programming where functions are deterministic and have no side effects. That makes the code predictable, testable, and easy to parallelise." — John Hughes, Why Functional Programming Matters (1990)
Core idea
A function is pure if it satisfies two rules:
- Same input → same output (deterministic).
- No side effects — it does not write to a file, it does not change global variables, it does not print, it does not touch the network, time, or randomness.
What is a "side effect"
Anything that goes beyond returning a value:
| Side effect | Example |
|---|---|
| Changing a global variable | count += 1 where count is module-level |
| Mutating an argument | lst.append(x) (mutating the caller's list) |
| I/O | print(), open(), requests.get() |
| Time or randomness | datetime.now(), random.random() |
| Exception (technically a side effect, but accepted) | raise ValueError(...) |
| Changing object state | self.count += 1 inside a method |
Why it matters
| Pure function | Impure function |
|---|---|
One line to test: assert f(2) == 4 |
Needs mocks, fixtures, DB, time |
| Safe to run in parallel | Race conditions, deadlocks |
Cacheable (@functools.cache) |
Not cacheable, the result may change |
| Everything that affects the result is in the signature | You have to read the body to understand the dependencies |
| Calls can be reordered or optimised | Order of calls is critical |
| Reasonable: "what you put in is what you get out" | "What if someone already changed it?" |
Example 1: time dependency
❌ Impure
from datetime import datetime
def greeting() -> str:
hour = datetime.now().hour
return "Good morning" if hour < 12 else "Good afternoon"
- Call at 11:59 → "Good morning".
- Call at 12:01 → "Good afternoon".
- The test has to mock
datetime.now(). Painful.
✅ Pure
def greeting(hour: int) -> str:
return "Good morning" if hour < 12 else "Good afternoon"
# called from the real world:
print(greeting(datetime.now().hour))
Now the test is assert greeting(8) == "Good morning". One line.
Example 2: mutating the argument
❌ Impure (mutates the input)
def add_default_tax(prices: list[float]) -> list[float]:
for i, p in enumerate(prices):
prices[i] = p * 1.20 # MUTATES the caller's list!
return prices
The caller does not expect their list to change. Somewhere else, the program will fail with "where did this 1.20× come from?".
✅ Pure (returns a new list)
def with_tax(prices: list[float], rate: float) -> list[float]:
return [p * (1 + rate) for p in prices]
Example 3: I/O inside the logic
❌ Impure
def calculate_total(qty: int) -> float:
price = float(open("price.txt").read()) # I/O! the file may be missing or changed
print(f"Calculating for qty={qty}") # I/O!
return qty * price * 1.20
✅ Pure
def calculate_total(qty: int, price: float, vat: float) -> float:
return qty * price * (1 + vat)
# I/O lives outside:
price = float(open("price.txt").read())
total = calculate_total(qty=5, price=price, vat=0.20)
print(f"Calculating for qty=5: {total}")
Example 4: global state
❌ Impure
_call_count = 0
def next_id() -> int:
global _call_count
_call_count += 1
return _call_count
Same "input" (empty) returns a different output every time. Hard to test, impossible to call safely from multiple threads.
✅ Pure (state is passed explicitly)
def next_id(current: int) -> int:
return current + 1
Or wrap it in a class with controlled lifetime. Just not a global.
Example 5: caching works only on pure functions
from functools import cache
@cache
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
@cache remembers the result for an input. It works only because fib is pure: the same n always produces the same result.
Apply @cache to an impure function and you get strange bugs:
@cache
def current_user_id(): # impure: reads request context
return request.user.id # ← caches the first call FOREVER
Functional Core, Imperative Shell
A strategy for building programs out of pure functions:
┌────────────────────────────────────────┐
│ IMPERATIVE SHELL │ ← impure: I/O, time, network
│ load_users() / save_results() │
│ datetime.now() / requests.get() │
│ │
│ ┌──────────────────────────────┐ │
│ │ FUNCTIONAL CORE │ │ ← pure: computation only
│ │ calculate(users, now) → │ │ ← easy to test
│ │ process_orders(...) → ... │ │ ← easy to parallelise
│ └──────────────────────────────┘ │
└────────────────────────────────────────┘
The "dirty" parts (I/O, time, randomness) are passed into pure functions as arguments instead of being fetched inside.
Making an impure function pure
The general recipe: anything fetched from outside, pass it as a parameter.
| Was (impure) | Is now (pure) |
|---|---|
datetime.now() inside |
now: datetime parameter |
random.random() inside |
seed: int or rng: Random parameter |
open(...) inside |
data: bytes parameter |
os.environ[...] inside |
config: Config parameter |
Changing self.x |
Return a new value, do not mutate |
When purity is impossible or not worth it
- The outer edge of the program —
main, the request handler, the CLI parser. I/O must be there. - Logging — technically a side effect, but very useful. No need to avoid it out of dogma.
- Exceptions /
raise— also a way out of the function, but in Python it is conventionally treated as acceptable for pure functions (strict FP would say it breaks referential transparency). - Caching inside —
@cacheby itself does not make the function impure to the outside observer.
Rule: purity lives in the core. At the edges, be pragmatic.
Rules of thumb
- If the function returns the same result for the same arguments, it is deterministic.
- If it can be called in any order without difference, it has no side effects.
- Push I/O, time, and randomness outward — pass them as parameters.
- Do not mutate what you got from outside — return a new object.
- Tests without mocks are a sign of a pure function. If you need
unittest.mockto test it, the function has side effects.
One-line summary
Same input in, same output out, and nothing else. Easier to test, easier to reason about, easier to parallelise.