1.Pure functions
A pure function returns a value that depends only on its arguments, and changes nothing outside itself — no global variable, no file, no argument mutated in place. Call it twice with the same input and it gives the same answer, every time.
Key features
- Same arguments in, same return value out — every single call, forever
- No side effects: no global write, no file write, no mutating an argument
- Never depends on hidden state — no reading a global, clock, or random source
- Easy to test: no setup, no mocking, just call it and check the return value
- Safe to call from multiple threads at once — nothing shared gets fought over
What makes a function impure
- Pure
- Reads only its own arguments
- Returns a value, changes nothing else
- Same input always gives the same output
- Impure
- Reads or writes state outside itself
- A global here accumulates across calls
- Same input can give a different output
Command
def add_tax(price, rate): # pure: output depends only on price and rate
return price * (1 + rate)
add_tax(100, 0.08) # 108.0
add_tax(100, 0.08) # 108.0 — identical call, identical resultA pure function only reads its arguments and only returns a value — no global, no file, no mutated argument. Same input always means same output.