Write a Pure Function Without Side Effects in Python

Defines a pure function that adds one to a number without modifying external state.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

10 lines
Python 3.9+
def add_one(x: int) -> int:
    """Adds 1 to the input without modifying any external state."""
    return x + 1

if __name__ == "__main__":
    original = 5
    result = add_one(original)
    print(f"Original: {original}")
    print(f"Result: {result}")
    print(f"Original unchanged: {original}")

Output

stdout
Original: 5
Result: 6
Original unchanged: 5

How it works

This function is pure because it always returns the same output for the same input and does not modify any external state. The return x + 1 operation only creates a new integer, leaving x untouched. The calling code keeps original intact, proving that the function has no side effects. Pure functions are easier to test, debug, and reason about because they depend only on their arguments.

Common mistakes

  • Modifying a global variable inside the function breaks purity.
  • Using mutable default arguments like `def add_one(x, lst=[])` introduces hidden state.
  • Calling `print()` or `time.sleep()` inside the function for non-debugging purposes adds side effects.
  • Assuming that passing mutable objects (like lists) means you can change them without affecting the caller.

Variations

  1. Add multiple numbers by taking two parameters: `def add(a, b): return a + b`.
  2. Use a lambda: `add_one = lambda x: x + 1`.

Real-world use cases

  • Implementing reduction operations like `sum()` that rely on pure addition.
  • Writing map-like transforms in data pipelines that leave input data unchanged.
  • Building unit tests where a function's output is deterministic and side-effect-free.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.