In this lesson, you will learn how to distinguish between "pure" functions that only calculate results and functions that create "side effects" by changing the world around them.
What is a Pure Function?
A pure function is a function that behaves like a mathematical formula: for the same input, it will always return the same output. Importantly, it does not change anything outside of itself. It takes data in, processes it, and sends a result back without touching global variables, printing to the console, or modifying lists you passed into it.
def add_numbers(a, b):
return a + b
No matter how many times you call add_numbers(2, 3), it always returns 5. It doesn’t modify your program’s state; it just does its job and returns the value.
What is a Side Effect?
A side effect occurs when a function does something "extra" beyond just returning a value. This happens if the function changes a variable defined outside its local scope, writes to a file, or prints to the screen.
Consider this example:
total = 0
def add_to_total(n):
global total
total += n # Side effect: modifying a global variable
return total
In this case, add_to_total is not pure because it modifies the total variable defined outside the function. If you call this function twice with the same input, the result changes because the global state has been altered.
Why Does It Matter?
Pure functions are much easier to debug and test because they don't have hidden dependencies. If your code is full of functions that reach out and change global variables (side effects), it becomes very difficult to track down where a variable’s value changed unexpectedly.
As you design your programs, try to write functions that focus purely on the transformation of data. Keep the parts of your code that produce side effects (like printing or updating global configurations) isolated from the logic that performs your calculations.
Key Takeaway: A pure function relies only on its arguments to produce an output and avoids modifying any state outside of its own local scope.