logo

Pure Functions

A pure function has two properties: it always returns the same output for the same input, and it doesn't change anything outside itself.

# Pure - just calculates and returns
def add(a, b):
    return a + b

# Impure - modifies external state
total = 0
def add_to_total(x):
    global total
    total += x

Pure functions are predictable. You can call them a thousand times and always know what you'll get. They're easy to test - no setup, no cleanup, just input and expected output.

Impure functions depend on or modify the world around them: global variables, files, databases, network calls. They're necessary, but harder to reason about.

The functional approach: keep the core logic pure, push impurity to the edges of your program.

I cover pure functions in depth in my Functional Programming course.