What is Scope? & LEGB
M3-R5.1 · Chapter 8: Scope and Modules · 4 min read
What is Scope ?
In Python, scope refers to the region of a program where a particular variable (name) is accessible. Python uses a namespace to manage these variables.
Key Terms
|
Term |
Meaning |
|
Name |
A variable identifier (e.g., x, total, my_func) |
|
Object |
The actual data the name refers to (e.g., 42, 'Hello', [1,2,3]) |
|
Scope |
The region where a name is visible and accessible |
|
Namespace |
A dictionary-like mapping of names to objects |
|
Binding |
Assigning a name to an object using the = operator |
Types of Scope
- Local Scope: Variables defined inside a function. Accessible only within that function.
- Enclosing Scope: Variables in the outer function when functions are nested.
- Global Scope: Variables defined at the top level of a module/script.
- Built-in Scope: Python pre-defined names like print(), len(), range(), etc.
Example
x = 10 # Global scope
def my_func():
y = 20 # Local scope
print(x) # Accesses global x -> 10
print(y) # Accesses local y -> 20
my_func()
# print(y) # NameError! y is local to my_func
Note: A name assigned inside a function is local to that function by default, even if a global variable with the same name exists.
The LEGB Rule
The LEGB Rule is the name resolution order Python follows when looking up a variable.
Python searches scopes in the fixed order L -> E -> G -> B. It stops at the first match.
If not found anywhere, a NameError is raised.
|
Letter |
Full Name |
Where Defined |
Example |
|
L |
Local |
Inside current function |
x = 1 inside def f() |
|
E |
Enclosing |
Outer function (nested) |
x in outer() accessed by inner() |
|
G |
Global |
Module top level |
x = 10 outside all functions |
|
B |
Built-in |
Python interpreter |
print(), len(), range() |
L — Local Scope
def greet():
name = 'Alice' # Local variable
print(name) # Found in Local -> Alice
E — Enclosing Scope (Nested Functions)
def outer():
msg = 'Hello' # Enclosing variable
def inner():
print(msg) # Found in Enclosing -> Hello
inner()
outer()
G — Global Scope
total = 100 # Global variable
def show():
print(total) # Found in Global -> 100
B — Built-in Scope
print(len('Python')) # len() is from Built-in scope -> 6
The global Keyword
To modify a global variable inside a function, use the global keyword. Without it, Python creates a new local variable instead.
count = 0
def increment():
global count # Declare intent to use global
count += 1
increment()
increment()
print(count) # 2
Note: Without 'global count', the statement count += 1 causes UnboundLocalError because Python treats count as an uninitialized local variable.
The nonlocal Keyword
Used in nested functions to modify a variable from the enclosing (outer) function's scope.
def outer():
x = 10
def inner():
nonlocal x # Refers to outer's x, not global
x += 5
inner()
print(x) # 15
outer()