Write a Pure Function Without Side Effects in Python
Defines a pure function that adds one to a number without modifying external state.
Python code
10 linesdef 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
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
- Add multiple numbers by taking two parameters: `def add(a, b): return a + b`.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.