In this lesson, you will learn how to read data defined in your global scope from inside a function and why relying on these external values can lead to tricky bugs.
Reading the Global Scope
When you define a variable outside of any function, it lives in the global scope. Python functions are designed to look for variables first in their own local scope, but if a variable isn't found there, Python will automatically "reach out" to the global scope to see if it exists.
This means you can easily reference global constants or configuration settings inside your functions without passing them as arguments.
# A global configuration variable
discount_rate = 0.10
def apply_discount(price: float) -> float:
# Python finds 'discount_rate' in the global scope
return price - (price * discount_rate)
print(apply_discount(100.0)) # Output: 90.0
The Risk of External State
While reading a global variable is technically simple, it often makes your functions harder to predict. If a function relies on a global variable, its behavior is no longer solely defined by its arguments.
If you rename the global variable or accidentally change its value elsewhere in your program, your function might start returning incorrect results without any warning. This violates the principle of modularity, as your function now has a "hidden dependency" on the code outside of it.
For instance, if another part of your code changes discount_rate to 0.50, the apply_discount function will suddenly change its output even though you didn't change the function code itself. This makes debugging difficult because the source of a logic error might be far away from where the function is actually called.
To keep your code clean and testable, it is almost always better to pass necessary values into the function as arguments rather than reaching into the global scope. This makes the function's requirements explicit and ensures it behaves consistently every time you call it.
Key Takeaway: While functions can automatically read global variables, relying on them creates hidden dependencies that make your code fragile and harder to debug; pass data explicitly through arguments whenever possible.