Python Scope & LEGB Rule: Mastering Variable Visibility

Introduction to Python Scope
In programming, Scope refers to the region of a program where a specific variable is accessible. Simply put, it determines the "visibility" of your variables and functions.
Understanding scope is crucial for avoiding Name Collisions (where two different parts of your code use the same name for different purposes) and for writing clean, modular code.
What is a Namespace?
Before diving into scope, we must understand Namespaces. A namespace is essentially a dictionary where keys are variable names and values are the objects themselves.
Python uses namespaces to keep track of variables in different areas of your code. For example, the os module has its own namespace, allowing you to have a variable named getcwd in your script without conflicting with os.getcwd().
The LEGB Rule: Python’s Lookup Strategy
When you reference a variable, Python searches for it in a specific order. This is known as the LEGB Rule:
- L: Local Scope — Inside the current function or lambda.
- E: Enclosing Scope — Inside any enclosing (outer) functions.
- G: Global Scope — At the top level of the script or module.
- B: Built-in Scope — Reserved keywords and built-in functions like
len,int,print.
1. Local (Function) Scope
Variables defined inside a function belong to that function’s local scope. They are created when the function is called and destroyed when it returns.
1def my_function():
2 local_var = "I exist only here"
3 print(local_var)
4
5my_function()
6# print(local_var) # This would raise a NameError2. Enclosing (Nonlocal) Scope
This occurs in nested functions. The "outer" function’s local scope becomes the "enclosing" scope for the "inner" function.
1def outer():
2 outer_var = "Outer space"
3
4 def inner():
5 print(outer_var) # Accessing enclosing scope
6
7 inner()
8
9outer()3. Global (Module) Scope
The global scope is the top-most level of your Python script. Variables defined here are visible throughout the entire file.
1global_count = 10
2
3def show_count():
4 print(f"Current count is {global_count}")
5
6show_count()4. Built-in Scope
This is the widest scope, containing all of Python’s built-in objects. It’s always available.
Avoid Shadowing
Never name your variables after built-in functions (e.g., `list = [1, 2]`). Doing so 'shadows' the built-in name, making the original `list()` function inaccessible in that scope!
Modifying Scope: global & nonlocal
Normally, you can read variables from outer scopes, but you cannot modify them. To do so, you need special keywords.
The global Keyword
Used to modify a variable defined at the top level of your script from within a function.
1counter = 0
2
3def increment():
4 global counter
5 counter += 1
6
7increment()
8print(counter) # Output: 1The nonlocal Keyword
Used in nested functions to modify a variable in the enclosing (outer) function.
1def outer():
2 x = "Initial"
3
4 def inner():
5 nonlocal x
6 x = "Modified by inner"
7
8 inner()
9 print(x)
10
11outer() # Output: Modified by innerPython Scope Cheat Sheet
| Operation | Local Code | Enclosed Code | Global Code | Built-in |
|---|---|---|---|---|
| Access Local | ✓ | ✘ | ✘ | ✘ |
| Modify Local | ✓ | ✘ | ✘ | ✘ |
| Access Enclosing | ✓ | ✓ | ✘ | ✘ |
| Modify Enclosing | nonlocal | ✓ | ✘ | ✘ |
| Access Global | ✓ | ✓ | ✓ | ✘ |
| Modify Global | global | global | ✓ | ✘ |
| Access Built-in | ✓ | ✓ | ✓ | ✓ |
Conclusion
Mastering the LEGB rule and knowing when to use global or nonlocal is a hallmark of an intermediate Python developer. It allows you to build complex, nested architectures without losing track of your data!
Up Next
Ready for more? Let's explore Python Inheritance, where we apply these scoping rules to Class hierarchies.
hear your feedback.
Till then , keep coding !
