Shadowing: When Names Collide
What You'll Learn
You'll discover what happens when a local variable has the same name as a global variable, and how to handle this "shadowing" behavior.
The Collision Problem
Imagine two people named "Alex" in the same building—one works on the ground floor (global) and one on the third floor (local). When you're on the third floor and call out "Alex," the local Alex responds, and the ground-floor Alex is temporarily "hidden" from view.
Shadowing occurs when you declare a local variable with the same name as a global variable. Inside that function or block, the local variable takes priority—it "shadows" or hides the global one. The global variable still exists, but you can't access it directly within that scope.
How It Works
When a function defines a variable named count and there's also a global variable named count, the function will always use its own local version. The global count is invisible inside that function.
count = 10 # global variable
def my_function():
count = 5 # local variable shadows the global
# Inside here, count refers to 5, not 10
Handling Name Conflicts
Best practice: Avoid shadowing by using distinct names. If count is global, use local_count or temp_count for the local variable.
If you must work with both, most languages provide ways to explicitly access the global variable (keywords or syntax), but preventing shadowing through clear naming is cleaner and less error-prone.
Why This Matters
Shadowing can cause subtle bugs when you think you're modifying a global variable but are actually only changing a local copy. Understanding scope boundaries helps you predict which variable your code actually references.
Key Takeaway: When a local variable has the same name as a global variable, the local one shadows (hides) the global one within that scope. Avoid shadowing by using unique, descriptive names.