1. What Is a Scope
A scope is the region in a program in which a name can be accessed and resolved.
In Python, a name can refer to a variable, function, class, module, or another object. When code accesses a name, the interpreter needs to determine which binding that name corresponds to.
For example:
name = "global"
def greet():
name = "local"
print(name)
greet()
print(name)
Output:
local
global
The same name name can be bound to different objects in different scopes. The name inside the function does not automatically overwrite the module-level name.
Two concepts need to be distinguished:
- Scope: the region in which a name can be looked up and accessed.
- Namespace: the mapping between names and objects, which can usually be thought of as a dictionary.
The scope determines the rules for name lookup, while the namespace holds the objects that the names actually correspond to.
2. The Four LEGB Scopes
LEGB is an acronym for the four kinds of name lookup ranges:
| Level | Full name | Meaning | Typical location |
|---|---|---|---|
| L | Local | Local scope | Inside the current function |
| E | Enclosing | Enclosing function scope | The enclosing function of a nested function |
| G | Global | Global scope | The current module |
| B | Built-in | Built-in scope | The Python built-in namespace |
When looking up an ordinary name, Python usually follows this order:
Local
↓ not found
Enclosing
↓ not found
Global
↓ not found
Built-in
↓ not found
NameError
The corresponding lookup process:
flowchart TD
A["Access a name"] --> B["Look up Local scope"]
B --> C{"Name found?"}
C -->|Yes| H["Return the corresponding object"]
C -->|No| D["Look up Enclosing scope"]
D --> E{"Name found?"}
E -->|Yes| H
E -->|No| F["Look up Global (current module)"]
F --> G{"Name found?"}
G -->|Yes| H
G -->|No| I["Look up Built-in scope"]
I --> J{"Name found?"}
J -->|Yes| H
J -->|No| K["Raise NameError"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The core principle is: start from the innermost level, and stop as soon as the first matching name is found.
The four scope levels are analyzed below.
3. Local: Local Scope
Local refers to the local scope formed while the current function is executing.
Variables defined inside a function usually belong to that function's local names.
def calculate():
price = 100
quantity = 3
total = price * quantity
print(total)
calculate()
Output:
300
Here price, quantity, and total are all local names of calculate().
While the function is executing, these names can be accessed; outside the function they cannot be accessed directly by their ordinary names:
def calculate():
price = 100
calculate()
print(price)
Output:
NameError: name 'price' is not defined
3.1 Determining Local Names
Python has an important characteristic when deciding what counts as a function's local variable: usually, while the function body is being compiled, it determines whether a name is local based on name-binding operations.
For example:
price = 100
def calculate():
print(price)
price = 200
calculate()
This code does not print the global variable price; instead it raises:
UnboundLocalError: cannot access local variable 'price' where it is not associated with a value
The reason is that the function body contains:
price = 200
Therefore, Python treats price as a local name of the current function. When print(price) executes, the local name has not yet been bound to an object, so an UnboundLocalError occurs.
You can fix it with the following code:
price = 100
def calculate():
price = 200
print(price)
calculate()
Output:
200
If you really do need to read and modify a global variable, you must use a global declaration, which is covered in detail later.
3.2 Local Scope and Function Calls
Every function call creates its own independent local execution environment.
def counter():
count = 0
count += 1
print(count)
counter()
counter()
counter()
Output:
1
1
1
Each call recreates the local name count, so the local binding from the previous call is not retained automatically.
Note that a local name leaving its scope does not mean the object it references is necessarily destroyed immediately. If the object is still referenced by other names or data structures, it can continue to exist.
IV. Enclosing: The Outer Function Scope
Enclosing refers to the function scope outside a nested function.
When a function is defined inside another function, the inner function can access names in the outer function.
def outer():
message = "Hello from outer"
def inner():
print(message)
inner()
outer()
Output:
Hello from outer
inner() does not define message itself, nor does it find it in the module's global namespace, so the lookup continues into the scope of the outer function outer().
4.1 Multi-Level Nested Functions
Enclosing is not limited to the immediately enclosing function; the lookup can continue further outward.
def level_one():
message = "level one"
def level_two():
def level_three():
print(message)
level_three()
level_two()
level_one()
Output:
level one
When looking up message:
- Look in the Local scope of
level_three(). - Look in the Enclosing scope of
level_two(). - Look in the Enclosing scope of
level_one(). - The name is found and the corresponding object is returned.
4.2 Closures and the Enclosing Scope
A closure is an important application of the Enclosing scope.
When an inner function references a variable from an outer function, the inner function can still access the retained outer binding even after the outer function has finished executing.
def make_counter():
count = 0
def counter():
print(count)
return counter
my_counter = make_counter()
my_counter()
Output:
0
After make_counter() finishes executing, the local name count has left the original function's execution, but the returned counter function still references it, so the relevant binding can continue to exist.
4.3 Modifying Variables in a Closure
Inner functions can read variables from the outer function by default, but if you need to rebind an outer variable, you need to use nonlocal.
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
counter = make_counter()
print(counter())
print(counter())
print(counter())
Output:
1
2
3
nonlocal count means binding count to the nearest outer function scope that contains that name, rather than creating a new local name in the current function.
Note the following:
nonlocalcan only refer to a name that already exists in an outer function scope.- It cannot directly refer to module global variables.
- Class scope is not treated as an ordinary enclosing function scope for methods.
V. Global: Global Scope
Global refers to the global namespace of the current module.
Variables, functions, and classes defined at the top level of a module usually belong to the module global scope.
site_name = "Python Tutorial"
def show_site():
print(site_name)
show_site()
Output:
Python Tutorial
If site_name is not found inside the function, the lookup continues in the current module's global namespace.
5.1 Reading Global Variables
A function can directly read global variables without using global.
count = 100
def show_count():
print(count)
show_count()
Output:
100
This is because it only reads the global name; it does not rebind it.
5.2 Modifying a Global Variable Requires global
If you need to rebind a global name inside a function, you must use global.
count = 100
def update_count():
global count
count = 200
update_count()
print(count)
Output:
200
global count declares that count in the current function refers to the global name in the current module, rather than creating a local name.
If you do not declare global:
count = 100
def update_count():
count = 200
update_count()
print(count)
Output:
100
An assignment inside the function only creates or updates a local name; it does not modify the module global name.
5.3 Modifying a Global Mutable Object Does Not Necessarily Require global
There is a common point of confusion here: modifying an object's contents and rebinding a name are two different things.
items = []
def add_item():
items.append("Python")
add_item()
print(items)
Output:
['Python']
Here, global is not used because the function merely uses the global name items to find the list object, then calls a list method to modify the object's contents; it does not rebind items.
But if you use reassignment:
items = []
def replace_items():
global items
items = ["Python", "Java"]
replace_items()
print(items)
then you need to use global.
This can be summarized as:
| Operation | Whether global is required |
|---|---|
| Read a global variable | Not required |
| Modify elements of a global list | Not required |
| Call a method on a global object to modify its contents | Usually not required |
| Reassign a global name | Required |
| Use augmented assignment on a global name | Usually required |
For example:
count = 10
def increase():
global count
count += 1
count += 1 involves an assignment binding to a name, so global is required.
5.4 The Scope of global
global refers to the global namespace of the current module, not a set of global variables shared by all modules across the entire Python process.
For example:
# module_a.py
count = 10
# module_b.py
import module_a
count = 20
print(count)
print(module_a.count)
Output:
20
10
module_a and module_b each have their own module global namespace.
Therefore, Python's global should not be understood as a mechanism for sharing variables across modules.
VI. Built-in: The Built-in Scope
Built-in refers to the built-in namespace provided by Python.
Python includes many commonly used functions, types, and exceptions, for example:
print(): outputs content.len(): gets the length of an object.range(): generates a sequence of integers.list: the list type.dict: the dictionary type.str: the string type.int: the integer type.Exception: the base class for common exceptions.ValueError: the value error exception.
Only when a name is not found in Local, Enclosing, or Global does Python continue searching Built-in.
def show():
print(len([1, 2, 3]))
show()
Output:
3
len is not defined inside the function, nor is it defined in the module global namespace, so Python ultimately finds it in the built-in namespace.
6.1 Inspecting the Built-in Namespace
You can inspect Python's built-in namespace through the builtins module:
import builtins
print(builtins.len([1, 2, 3]))
print(builtins.sum([1, 2, 3]))
print(builtins.max([1, 2, 3]))
Output:
3
6
3
You can also inspect which names exist in the built-in namespace:
import builtins
print(dir(builtins))
6.2 Built-in Names Can Be Shadowed
Because Global has a higher lookup priority than Built-in, module global names can shadow built-in names.
len = 100
print(len)
Output:
100
At this point len no longer refers to the built-in function but to the integer object 100.
If you try to call it:
len = 100
print(len([1, 2, 3]))
You will get:
TypeError: 'int' object is not callable
Because Python found the global name len, it does not continue searching the built-in namespace.
You can explicitly access the original built-in function through the builtins module:
import builtins
len = 100
print(builtins.len([1, 2, 3]))
Output:
3
In engineering practice, avoid using built-in names such as list, str, dict, len, and sum as variable names, to avoid name shadowing.
VII. Name Shadowing and Scope Priority
Name shadowing means that an inner scope defines a name with the same name as one in an outer scope, so that the outer name cannot be accessed directly in the current lookup environment.
name = "global"
def outer():
name = "enclosing"
def inner():
name = "local"
print(name)
inner()
outer()
Output:
local
Here there are three names with the same name:
namein the module global scope.namein the outer function scope.namein the inner function scope.
Because Local has the highest priority, name in inner() refers to the local name.
7.1 Variables with the Same Name Across Four Scope Levels
name = "Global"
def outer():
name = "Enclosing"
def inner():
name = "Local"
print(name)
inner()
outer()
Output:
Local
If the local definition in inner() is removed:
name = "Global"
def outer():
name = "Enclosing"
def inner():
print(name)
inner()
outer()
Output:
Enclosing
If the definition in outer() is then removed:
name = "Global"
def outer():
def inner():
print(name)
inner()
outer()
Output:
Global
If name is also not defined in the module global scope, Python will look in the built-in namespace last.
7.2 Engineering Risks of Name Shadowing
Name shadowing can cause the following problems:
- Accidentally overwriting a variable in an outer function.
- Using a built-in function name as an ordinary variable.
- Making it difficult to determine which object a name actually refers to when reading code.
- Introducing new name conflicts after function refactoring.
- Mistakenly believing during debugging that an outer variable was modified when a local variable was actually modified.
Recommended practices:
- Avoid reusing variable names with different meanings.
- Avoid using Python built-in functions and types as variable names.
- Explicitly use
nonlocalorglobalfor variables whose outer bindings need to be modified. - Use variable names with business meaning in more complex functions.
VIII. Relationship Between LEGB and global, nonlocal
LEGB describes how names are looked up, whereas global and nonlocal are used to change which scope a name inside a function is bound to.
The two are closely related, but they are not the same concept.
8.1 global: Binding to the Module Global Scope
count = 10
def update():
global count
count = 20
update()
print(count)
Output:
20
global declares count in the current function as a module global name.
8.2 nonlocal: Binding to an Outer Function Scope
def outer():
count = 10
def inner():
nonlocal count
count = 20
inner()
print(count)
outer()
Output:
20
nonlocal binds count in the current function to an existing name in the nearest outer function scope.
8.3 Differences Between global and nonlocal
| Aspect | global | nonlocal |
|---|---|---|
| Binding target | The current module global scope | The nearest outer function scope |
| Whether the target name must already exist | A global binding can be created after the declaration | An outer function binding must already exist |
| Whether it can access module global variables | Yes | No |
| Common use cases | Modifying module-level state | Modifying closure state |
| Whether it creates a new local binding | No | No |
Both have syntactic placement requirements: the declaration must appear before the corresponding name is used or assigned in the function body.
For example, the following code is invalid:
count = 10
def update():
print(count)
global count
Python will report a syntax error because global count appears after count is used.