On this page

Pure Functions in Python: A Functional Programming Guide

Published on July 6, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A pure function is the fundamental building block of functional programming. It is a function that, given the same arguments, always returns the same result and produces no observable side effects. This means the function's output depends solely on its inputs, and it does not modify any external state — no global variables, no mutations of arguments, no I/O operations, no printing to the console. This seemingly simple constraint unlocks profound benefits: pure functions are easier to test, reason about, and debug; they enable safe concurrency and parallel execution; and they make code more predictable and maintainable. While Python is not a purely functional language, it fully supports the creation and use of pure functions, and adopting this style can dramatically improve the quality of your code. This lesson explains what pure functions are, why they matter, how to write them in Python, and how to recognise and avoid common impurities.


What Is a Pure Function?​

A pure function is the computational analogue of a mathematical function. It has two essential properties:

1. Determinism: Same Input, Same Output​

A pure function always produces the same result when given the same arguments. It does not depend on any hidden state — no global variables, no non‑local variables, no mutable reference arguments, no input from I/O devices, and no randomness.


def add(a, b):

    return a + b



def square(x):

    return x * x

add(3, 5) always returns 8. square(9) always returns 81. No matter how many times you call them, with the same arguments, the result is identical.

Impure function (non‑deterministic):


import random



def roll_dice():

    return random.randint(1, 6)

roll_dice() can return any number from 1 to 6. Its output depends on the state of the random number generator, which is outside the function's control.

2. No Side Effects​

A pure function does not modify anything outside its own scope. It does not:

The internal work of a pure function is isolated from the rest of the program.


def calculate_area(length, width):

    return length * width

This function is pure because it only uses its inputs and returns a value. It has no side effects.

Impure function — has side effects:


total = 0



def add_to_total(a, b):

    global total

    total += a + b

    return total

This function modifies a global variable. Calling it twice with the same arguments does not produce the same result, because the output depends on the current value of total. It also has a side effect: it changes the global state.


Pure vs. Impure Functions: A Comparison​

Consider two functions that both compute the sum of a list — one pure and one impure.

Pure version:


def sum_pure(numbers):

    total = 0

    for n in numbers:

        total += n

    return total

This function takes a list, computes the sum, and returns it. It does not modify the input list, does not depend on any external state, and does not produce side effects. Calling it repeatedly with the same list always yields the same result.

Impure version:


def sum_impure(numbers):

    global accumulator

    accumulator += sum(numbers)

    return accumulator

This function depends on a global accumulator variable. It modifies that variable, and its result is not deterministic — it depends on the current value of accumulator. Testing this function requires setting up and tearing down global state, which adds complexity and makes tests less reliable.


Why Pure Functions Matter​

Pure functions offer several compelling advantages that make them a cornerstone of functional programming.

Easier to Test​

Testing a pure function is straightforward: you provide inputs and check outputs. There is no need to set up or tear down external state, mock dependencies, or handle side effects. This simplicity makes tests faster, more reliable, and easier to write.

Easier to Reason About​

A pure function's behaviour is completely determined by its arguments. You do not need to understand the broader program state to know what a pure function will do. This reduces cognitive load and makes code easier to understand and maintain.

Safe for Concurrency​

Pure functions are inherently thread‑safe because they do not modify shared state. Multiple threads can execute pure functions simultaneously without the risk of data races or corrupted state. This makes pure functions ideal for concurrent and parallel programming.

Enables Caching and Memoization​

Because pure functions always return the same result for the same inputs, their results can be cached. Python's functools.lru_cache decorator can be applied to pure functions to automatically memoize results, dramatically improving performance for expensive computations.


from functools import lru_cache



@lru_cache(maxsize=None)

def fibonacci(n):

    if n <= 1:

        return n

    return fibonacci(n - 1) + fibonacci(n - 2)

Supports Referential Transparency​

Pure functions enable referential transparency: you can replace a function call with its return value without changing the program's behaviour. This property allows for equational reasoning — you can reason about your code using simple algebraic substitutions, just like in mathematics.

Reduces Bugs​

Impure functions often introduce subtle bugs because they depend on hidden state or produce unintended side effects. By eliminating these sources of complexity, pure functions make programs more robust and less error‑prone.


How to Write Pure Functions in Python​

Writing pure functions in Python is a matter of discipline and awareness.

1. Use Only Input Parameters​

A pure function should only use values passed to it as arguments. It should not access global variables, non‑local variables, or class attributes.


# Pure

def greet(name):

    return f"Hello, {name}!"



# Impure

greeting_prefix = "Hello"



def greet_impure(name):

    return f"{greeting_prefix}, {name}!"

2. Avoid Mutating Arguments​

Do not modify the objects passed as arguments. If you need to return a modified version of an input, create a new object instead.


# Pure

def add_item(items, new_item):

    return items + [new_item]  # Creates a new list



# Impure

def add_item_impure(items, new_item):

    items.append(new_item)  # Mutates the original list

    return items

3. Avoid I/O Operations​

A pure function should not perform I/O: no printing, no file operations, no network requests, no database queries.


# Pure

def double(x):

    return x * 2



# Impure

def double_and_print(x):

    print(f"Doubling {x}")  # Side effect

    return x * 2

4. Avoid Raising Exceptions (Unless You Handle Them)​

Strictly speaking, raising an exception is a side effect. In functional programming, errors are typically handled by returning an error value (like None, an Optional, or an Either type) rather than raising exceptions. However, in Python, it is common to use exceptions even in otherwise pure functions, as long as the function's behaviour remains deterministic and the exception is used only for error signalling.

5. Use Immutable Data Structures​

Pure functions work best with immutable data. Use tuples instead of lists, frozensets instead of sets, and frozen dataclasses instead of mutable ones.


# Pure — uses immutable data

def process_coordinates(coords):

    x, y = coords

    return (x * 2, y * 2)



# Impure — modifies the input

def process_coordinates_impure(coords):

    coords[0] *= 2

    coords[1] *= 2

    return coords

Recognising Impure Functions​

Impure functions are sometimes necessary — Python programs must eventually interact with the outside world. The goal is not to eliminate all impurity, but to isolate it and minimise its impact.

Common Sources of Impurity​

Example: An Impure Function with Multiple Issues​


counter = 0



def process_items(items, multiplier):

    global counter

    result = []

    for i, item in enumerate(items):

        if item % 2 == 0:

            result.append(item * multiplier)

            counter += 1  # Modifies global state

        else:

            result.append(item)

            print(f"Skipping odd item: {item}")  # I/O side effect

    return result

This function is impure because it:

  1. Modifies a global variable (counter)
  2. Performs I/O (print)
  3. Its behaviour depends on the current value of counter

Practical Patterns for Pure Functions​

1. Write Small, Focused Functions​

Pure functions are easier to write and understand when they do one thing and do it well. Aim for functions that are small and focused.

2. Use functools for Function Composition​

The functools module provides tools for composing pure functions:


from functools import partial, reduce



# partial creates a new function with some arguments fixed

multiply_by_two = partial(lambda x, y: x * y, 2)

print(multiply_by_two(5))  # 10

3. Separate Pure Logic from Impure I/O​

A common pattern is to separate pure logic from impure operations:


# Pure function

def compute_average(numbers):

    return sum(numbers) / len(numbers)



# Impure wrapper

def read_numbers_and_compute_average(filename):

    with open(filename) as f:

        numbers = [int(line.strip()) for line in f]

    return compute_average(numbers)

This design makes the pure logic testable in isolation.

4. Use Type Hints for Clarity​

Type hints make it clear what a function expects and returns, which is especially helpful for pure functions:


from typing import List



def sum_list(numbers: List[int]) -> int:

    return sum(numbers)

Common Mistakes and How to Avoid Them​

1. Assuming a Function Is Pure Because It Only Reads Globals​

A function that reads a global variable is impure because the global can change:


# Impure

DEBUG = True



def log_if_debug(message):

    if DEBUG:

        print(message)

If DEBUG changes, the function's behaviour changes. To make it pure, pass the value as an argument.

2. Mutating Default Arguments​

Default arguments are evaluated once. Using a mutable default leads to shared state across calls:


# Impure

def add_item(item, items=[]):

    items.append(item)

    return items

Use None as the default and create a new object inside the function:


# Pure

def add_item(item, items=None):

    if items is None:

        items = []

    return items + [item]

3. Confusing Reassignment with Mutation​

Reassigning a variable is not mutation. Mutation changes the object itself:


# This reassigns x — it does not mutate the original object

x = x + 1



# This mutates the list in place

items.append(4)

Reassignment is safe; mutation is not.


Summary​

Pure functions are the foundation of functional programming in Python. A pure function is deterministic — it always returns the same result for the same inputs — and it produces no side effects. This simple constraint delivers powerful benefits: easier testing, simpler reasoning, safer concurrency, and more predictable code. While Python is not a purely functional language, it fully supports the creation and use of pure functions. By adopting the discipline of writing pure functions wherever possible, you can write code that is more robust, maintainable, and easier to understand. The key is to isolate impurity — separate the parts of your program that must interact with the outside world from the pure logic that can be tested and reasoned about in isolation.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Immutability

Next

Higher-Order Functions