Skip to content
BENIBIX Learn

Pure Function

Development🧭 Programming ParadigmsFunctional Programming

Also known as Pure Functions

A function that gives the same answer for the same input. It changes nothing else.

Think of it like

Think of it like a calculator. Press 2 plus 3, and you get 5 every single time.

Example

Jack's add(2, 3) gives 5 today, tomorrow and on every computer. His test only checks that one number.

Why it matters

Pure functions can be tested alone, cached and run in any order without surprises.

Definition

A pure function always gives the same output for the same input. It does nothing else: it does not change a variable outside, write a file or print. Everything it needs comes in through its inputs. That makes it easy to test, since you only check what comes back. It is the main building block of functional programming.

Example code

python
def add(a, b):
    return a + b

print(add(2, 3))  # 5
Same inputs, same answer, and nothing else is touched.

Common mistake

Reading the clock or a random number inside the function. The answer then changes even when the input does not.

Key takeaways

  1. 1
    Same in, same out. Every time, everywhere.
  2. 2
    No side effects. Nothing outside is changed.
  3. 3
    Easy to test. Check the answer, nothing else.