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:

  1. Same input → same output (deterministic).
  2. 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"

✅ 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

Rule: purity lives in the core. At the edges, be pragmatic.


Rules of thumb

  1. If the function returns the same result for the same arguments, it is deterministic.
  2. If it can be called in any order without difference, it has no side effects.
  3. Push I/O, time, and randomness outward — pass them as parameters.
  4. Do not mutate what you got from outside — return a new object.
  5. Tests without mocks are a sign of a pure function. If you need unittest.mock to 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.