This guide explains avoid hidden global state in functions through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
Hidden global state causes a function to depend on previous calls or outside changes. Pass inputs explicitly and return new state to make behavior predictable.
When and Why to Use It
The following example focuses on a practical use of Avoid Hidden Global State in Functions.
Step-by-Step Example
discount_rate = 0.15
def hidden_price(price):
return price * (1 - discount_rate)
def explicit_price(price, applied_discount):
return price * (1 - applied_discount)
print(hidden_price(100))
print(explicit_price(100, 0.15))
Understanding the Example
The outputs agree for now, but only explicit_price advertises the discount dependency in its signature.
Expected Output
85.0
85.0
Important Behavior and Edge Cases
A test that changes discount_rate can affect unrelated calls. Also avoid default mutable objects used as hidden accumulators.
Try It Yourself
Replace a global sales_tax variable with a required function parameter.
Common Beginner Mistakes
- A test that changes discount_rate can affect unrelated calls. Also avoid default mutable objects used as hidden accumulators.
- Confusing a returned value with printed output, or failing to verify a function’s behavior with different input values.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- Hidden global state causes a function to depend on previous calls or outside changes.
- The outputs agree for now, but only explicit_price advertises the discount dependency in its signature.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.