☼
⌃
☰

Side Effects

Table of Contents

A function produces a side effect when it modifies state outside its own scope beyond its return value. Side effects make code harder to reason about, test, and parallelise — because the function's behaviour depends on and alters context it does not own. See also: Determinism, Pure Functions.

Related: Functional Programming Determinism Pure Functions Immutability

What Counts as a Side Effect

PYTHON
# Modifying a global variable
total = 0
def add_to_total(x):
    global total
    total += x           # side effect: modifies external state

# Mutating an argument
def append_item(lst, item):
    lst.append(item)     # side effect: mutates the caller's list

# I/O
def log(message):
    print(message)       # side effect: writes to stdout

def save(data, path):
    with open(path, "w") as f:
        f.write(data)    # side effect: writes to disk

# Database write
def create_user(name):
    db.insert("users", {"name": name})   # side effect: external state change

# Network call
def notify(url, payload):
    requests.post(url, json=payload)     # side effect: external system call

Why They Are a Concern

Hard to test

A function with side effects requires setup and teardown — mocking databases, patching globals, capturing stdout. A pure function requires only inputs and assertions:

PYTHON
# Hard to test — depends on and modifies global
def process():
    global result
    result = compute_something()

# Easy to test — all inputs explicit, no external state
def process(data):
    return compute_something(data)

Spooky action at a distance

A change in one function unexpectedly breaks another because both share mutable state. The bug in B is caused by A, but A and B appear unrelated:

PYTHON
shared_list = [1, 2, 3]

def function_a():
    shared_list.append(4)    # mutates shared state

def function_b():
    return sum(shared_list)  # result depends on whether A ran first

Concurrency hazards

Side effects on shared state cause race conditions when functions run in parallel:

PYTHON
import threading

counter = 0

def increment():
    global counter
    counter += 1   # read-modify-write — not atomic, race condition

threads = [threading.Thread(target=increment) for _ in range(100)]
# counter may not be 100 after all threads finish

Managing Side Effects

The practical goal is not to eliminate side effects — programs must eventually do I/O — but to isolate them:

PYTHON
# Push side effects to the edges; keep core logic pure

# Pure core — easy to test, reason about, parallelise
def calculate_total(items: list[dict]) -> float:
    return sum(item["price"] * item["quantity"] for item in items)

# Side effect isolated at the boundary
def process_order(order_id: int) -> None:
    items = db.fetch_order_items(order_id)   # side effect: I/O
    total = calculate_total(items)           # pure
    db.save_total(order_id, total)           # side effect: I/O

Tips

  • Mutation of arguments is a particularly surprising side effect — callers rarely expect their data to change; prefer returning a new value to modifying in place
  • list.sort() mutates in place (side effect); sorted(list) returns a new list (no side effect) — know which Python built-ins mutate and which do not
  • When a function is hard to test, side effects are almost always the reason — refactor by extracting the pure logic into a separate function
  • Logging is a side effect but an accepted one — the convention is to treat logging as infrastructure rather than application logic and not worry about testing it