Course contentsShow
← Python
Lesson 156 of 1,0603. Functions and ModularizationFree lesson

Maintaining Functional Purity by Avoiding Global State

You will practice writing functions that avoid modifying global variables, ensuring your code remains predictable, testable, and free from hidden dependencies.

Maintaining Functional Purity by Avoiding Global State

In this lesson, you will learn how to make your functions more predictable by relying exclusively on their arguments rather than modifying variables outside their scope.

The Problem with Global State

When a function reaches outside its own "local" world to change a global variable, it creates a "hidden dependency." This makes code difficult to debug because you cannot tell what a function will do just by looking at its inputs. If the global variable changes somewhere else in your program, your function’s behavior changes unexpectedly, leading to bugs that are hard to track down.

Consider this example of impure code:

score = 0

def update_score(points):
    global score
    score += points  # Relying on a global variable

update_score(10)
print(score)  # Output: 10

The function update_score is "impure" because it depends on the global variable score. If you accidentally changed score elsewhere, the function would produce different results even if you passed it the same input.

Keeping It Pure

A "pure" function only interacts with data passed in through its parameters and communicates its result via the return statement. This makes the function a self-contained unit that is easy to test and reuse.

Here is the pure version of the same logic:

def calculate_new_score(current_score, points):
    return current_score + points

score = 0
score = calculate_new_score(score, 10)
print(score)  # Output: 10

By passing the score as an argument and returning the result, the function calculate_new_score doesn't care where the data came from or what happens to the variable outside of it. It does one thing, does it consistently, and leaves the rest of your program untouched. When you avoid modifying global state, your code becomes a predictable sequence of transformations rather than a tangled web of shared variables.

Key Takeaway: To keep your functions reliable and bug-free, always pass necessary data as arguments and return the result instead of modifying global variables from within the function body.