1. What Is Variable Scope?
Variable scope (Scope) refers to the range in a program where a variable name can be accessed and used.
For example:
name = "Alice"
def greet():
age = 25
print(name)
print(age)
greet()
print(name)
Output:
Alice
25
Alice
There are two different variables here:
name: defined outside the function, and can be accessed in the global scope.age: defined inside the function, and can only be accessed in the function's local scope.
If you access age outside the function:
def greet():
age = 25
greet()
print(age)
It will raise an exception:
NameError: name 'age' is not defined
This is because age is a local variable of the function, and it cannot be accessed directly from outside the function.
Variable scope mainly addresses three questions:
- Where can a variable be accessed?
- How are variables with the same name in different scopes distinguished?
- When a variable is modified inside a function, which scope is actually affected?
Python uses the LEGB rule to determine the lookup order for variable names, and uses global and nonlocal to control where variables are bound.
2. Local Variable
1. What Is a Local Variable?
A local variable is a variable defined inside a function, and its scope is usually the current function.
def calculate():
price = 100
quantity = 3
total = price * quantity
print(total)
calculate()
Output:
300
Here, price, quantity, and total are all local variables.
They can be used inside the calculate() function, but cannot be accessed directly outside it.
2. Scope of Local Variables
def first():
message = "Hello"
print(message)
def second():
message = "Python"
print(message)
first()
second()
Output:
Hello
Python
The two functions each define a local variable named message.
They belong to different function scopes and do not interfere with each other.
Even if the variable names are the same, that does not mean they are the same variable.
3. Local and Global Variables Can Have the Same Name
name = "Global Alice"
def greet():
name = "Local Bob"
print(name)
greet()
print(name)
Output:
Local Bob
Global Alice
A new local variable name is defined inside the function; it does not overwrite the global variable.
Variable relationship:
Global scope
name ─────> "Global Alice"
Function local scope
name ─────> "Local Bob"
The two names are bound to different objects.
4. What Happens to Local Variables After a Function Call Ends?
After a function call ends, the function's local execution environment is usually released, and the local names are no longer accessible.
def create_user():
username = "Alice"
return username
result = create_user()
print(result)
Output:
Alice
Although the local name username is no longer in the function's execution environment, the returned string object can still be accessed through result.
Note that the lifetime of a local variable name is not the same as the lifetime of the object itself.
If the object is still referenced by other variables, containers, or closures, it will not be destroyed immediately just because the function returned.
5. Assignment Rules for Local Variables
Inside a function, as long as there is a binding operation for a name, Python will usually treat that name as a local variable of the current function, unless its binding scope is changed by a global or nonlocal declaration.
For example:
number = 100
def calculate():
print(number)
number = 200
calculate()
This code will raise:
UnboundLocalError: cannot access local variable 'number' where it is not associated with a value
Why does it raise an error?
Because when Python analyzes the function code, it finds the assignment number = 200, and therefore treats number as a local variable of the function.
As a result, the earlier print(number) tries to read a local variable that has not yet been assigned, rather than reading the global variable.
This is also one of the most common errors involving Python local variables.
III. Global Variables
1. What is a global variable?
Variables defined at the top level of a module are usually called global variables.
app_name = "Python Learning"
version = "3.14"
def show_info():
print(app_name)
print(version)
show_info()
Output:
Python Learning
3.14
Inside a function, global variables can be read directly.
Global variables are usually used to hold module-level shared configuration, constants, and state information.
2. Functions can read global variables directly
language = "Python"
def show_language():
print(language)
show_language()
Output:
Python
When no local variable with the same name is defined inside the function, Python continues to look up the name in outer scopes.
If the corresponding name is found in the global scope, it can be read.
3. Modifying a global variable inside a function
If you want to rebind a global variable inside a function, you need to use global.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
Output:
2
global count means: the assignment to count inside the function acts on the global name in the current module, rather than creating a local variable.
4. What happens without global?
count = 0
def increment():
count = count + 1
increment()
It will raise:
UnboundLocalError
The reason is:
- The function body contains
count = count + 1. - Python treats
countas a local variable. - The expression on the right side needs to read the local variable
countfirst. - But at this point the local variable has not yet been assigned.
Therefore an exception occurs.
5. Basic syntax of global
global variable_name
You can declare one or more global names:
count = 0
total = 100
def update():
global count, total
count += 1
total += 10
update()
print(count)
print(total)
Output:
1
110
Things to note:
globalaffects name binding and assignment behavior.globaldoes not create a new global variable.globalrefers to the global namespace of the current module.- It cannot directly declare a variable from another module as a global variable of the current module.
6. Modifying a global mutable object does not necessarily require global
This is a very important point.
users = []
def add_user():
users.append("Alice")
add_user()
print(users)
Output:
['Alice']
Why is global not used here?
Because:
users.append("Alice")
What is modified is the list object itself; the name users is not rebound.
But if you reassign it:
users = []
def reset_users():
global users
users = []
reset_users()
then you need to use global.
Comparison:
| Operation | Requires global |
|---|---|
| Read a global variable | No |
| Modify contents of a global list | No |
| Modify contents of a global dictionary | No |
| Reassign a global variable | Yes |
Modify a global integer using += |
Yes |
| Make a global name point to a new object | Yes |
Pay special attention here: the behavior of += depends on the object type.
For immutable objects such as integers, += creates a new object and rebinds the name, so global is required.
For mutable objects such as lists, += usually extends the object in place, but you still cannot simply treat all augmented assignments as in-place modifications. You should judge based on the operation implementation of the specific type.
IV. nonlocal: Modifying Variables in an Outer Function
1. What Is nonlocal?
nonlocal is used in nested functions to declare that a name belongs to the nearest enclosing function scope, not the local scope of the current function.
For example:
def outer():
message = "Hello"
def inner():
nonlocal message
message = "Python"
inner()
print(message)
outer()
Output:
Python
There are two functions here:
outer(): the outer function.inner(): the inner function nested insideouter().
message is defined in outer().
If inner() wants to rebind message in the outer function, it needs to use nonlocal.
2. What Happens Without nonlocal?
def outer():
message = "Hello"
def inner():
message = "Python"
inner()
print(message)
outer()
Output:
Hello
Here, message = "Python" creates a local variable of inner().
It does not modify message in outer().
The relationship between the two variables:
outer local scope
message ─────> "Hello"
inner local scope
message ─────> "Python"
If we add nonlocal:
def outer():
message = "Hello"
def inner():
nonlocal message
message = "Python"
inner()
print(message)
outer()
Then the two functions access the same message name in the outer function.
3. Basic Syntax of nonlocal
nonlocal variable_name
You can declare multiple names:
def outer():
name = "Alice"
age = 20
def inner():
nonlocal name, age
name = "Bob"
age = 25
inner()
print(name, age)
outer()
Output:
Bob 25
4. nonlocal Requires an Existing Outer Binding
nonlocal can only refer to bindings that already exist in an outer function scope.
Incorrect example:
def outer():
def inner():
nonlocal message
message = "Hello"
inner()
outer()
It will raise:
SyntaxError: no binding for nonlocal 'message' found
Because message is not defined in the outer function.
Correct example:
def outer():
message = "Hello"
def inner():
nonlocal message
message = "Python"
inner()
outer()
5. nonlocal does not modify global variables
message = "Global"
def outer():
def inner():
nonlocal message
message = "Local"
inner()
outer()
This code will produce a syntax error.
Because message exists only in the global scope and has no corresponding enclosing function binding.
If you need to modify a global variable, use global, not nonlocal.
V. Differences between global and nonlocal
Both global and nonlocal are used to change the binding scope of names inside a function, but they point to different scopes.
| Comparison dimension | global | nonlocal |
|---|---|---|
| Scope | Module global scope | Nearest enclosing function scope |
| Common location | Regular function or nested function | Nested function |
| Whether an enclosing function variable is required | No | Yes |
| Whether module variables can be modified | Yes | No |
| Whether enclosing function variables can be modified | Cannot be done directly through it | Yes |
| Main purpose | Modify module-level name bindings | Modify name bindings in closures |
1. global example
count = 0
def outer():
def inner():
global count
count += 1
inner()
outer()
print(count)
Output:
1
global directly operates on module-level variables.
2. nonlocal example
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
print(count)
outer()
Output:
1
nonlocal operates on variables in the enclosing function.
3. Relationship of the three variable scopes
Module global scope
|
| global
v
Outer function scope
|
| nonlocal
v
Inner function scope
Note that this is only a schematic diagram to help understand variable binding scopes. Python name lookup also includes the built-in scope, and nonlocal always looks for the nearest enclosing function scope that has the corresponding binding.
VI. Python's LEGB name lookup rules
To understand local variables, global variables, and nonlocal, you also need to master the LEGB rule.
LEGB is the scope order Python follows when looking up variable names.
The four letters stand for the following:
| Letter | Name | Meaning |
|---|---|---|
| L | Local | Current function's local scope |
| E | Enclosing | Enclosing function scope |
| G | Global | Current module's global scope |
| B | Built-in | Python built-in scope |
When Python looks up a name, it usually follows this order:
Local
|
v
Enclosing
|
v
Global
|
v
Built-in
|
v
If not found, a NameError is raised
1. Local: Local Scope
def greet():
name = "Alice"
print(name)
greet()
name is defined inside the current function and is first found in the Local scope.
2. Enclosing: Enclosing Function Scope
def outer():
message = "Hello"
def inner():
print(message)
inner()
outer()
inner() does not define message internally, so the lookup moves outward to the enclosing function outer().
3. Global: the global scope
language = "Python"
def show():
print(language)
show()
Neither the function's own scope nor the enclosing function scope defines language, so the lookup continues into the module's global scope.
4. Built-in: the built-in scope
def show():
print(len([1, 2, 3]))
show()
len is not defined in the current function or in the global scope, so Python finally finds it in the built-in scope.
Common built-in names include:
printlenrangesummaxmintypeintstrlistdict
5. A complete LEGB example
name = "Global"
def outer():
name = "Enclosing"
def inner():
name = "Local"
print(name)
inner()
outer()
Output:
Local
Because the Local scope has the highest priority.
Now remove the innermost variable:
name = "Global"
def outer():
name = "Enclosing"
def inner():
print(name)
inner()
outer()
Output:
Enclosing
Then remove the enclosing variable as well:
name = "Global"
def outer():
def inner():
print(name)
inner()
outer()
Output:
Global
If name is not defined in the global scope either, Python continues on to the Built-in scope, and only raises NameError when it still cannot find it.
6. How LEGB relates to global and nonlocal
LEGB governs name lookup, while global and nonlocal mainly affect the rules for binding names inside a function.
global: tells Python that assignments to this name inside the current function target the module's global scope.nonlocal: tells Python that assignments to this name inside the current function target the nearest enclosing function scope.- No declaration: a name assigned inside a function is usually treated as a local variable.
Together, these three form the foundation of variable scope management in Python functions.
7. Closures and practical uses of nonlocal
The most typical use case for nonlocal is closures.
A closure means that an inner function references a variable from an outer function, and even after the outer function finishes executing, the inner function can still access those variables.
1. What is a closure?
def outer():
message = "Hello"
def inner():
print(message)
return inner
func = outer()
func()
Output:
Hello
Although outer() has already finished executing, the returned inner() can still access message.
This is because the inner function keeps a reference to the outer variable.
2. Implementing a counter with nonlocal
def create_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = create_counter()
print(counter())
print(counter())
print(counter())
Output:
1
2
3
Here:
countis defined in the outer function.increment()referencescount.nonlocalallows the inner function to rebind the outer variable.- Each call can access the state updated by the previous call.
3. Creating multiple independent counters
def create_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter_a = create_counter()
counter_b = create_counter()
print(counter_a())
print(counter_a())
print(counter_b())
print(counter_b())
Output:
1
2
1
2
Why do the two counters not affect each other?
Because each call to create_counter() creates a separate set of local state.
Each closure stores its own corresponding count binding.
4. Using nonlocal for state management
def create_user():
username = "Alice"
active = True
def update_name(new_name):
nonlocal username
username = new_name
def deactivate():
nonlocal active
active = False
def get_info():
return {
"username": username,
"active": active
}
return update_name, deactivate, get_info
update_name, deactivate, get_info = create_user()
update_name("Bob")
deactivate()
print(get_info())
Output:
{'username': 'Bob', 'active': False}
This approach encapsulates state inside the closure, exposing only a limited set of operation functions externally.
VIII. Variable Scope and Scope Resolution Details
1. Python determines local variables based on the entire function body
Python typically analyzes name bindings when compiling a function, rather than deciding on the fly which scope a variable belongs to as each line is executed.
For example:
number = 100
def test():
print(number)
if False:
number = 200
test()
Even though the assignment inside if False will never execute, number in the function is still determined to be a local variable.
Therefore, print(number) will raise UnboundLocalError.
This shows that local-variable determination and whether code actually runs are two separate issues.
2. Placement of the global declaration
The global declaration must appear before any conflicting use or assignment of that name.
Incorrect example:
count = 0
def update():
count += 1
global count
This will raise SyntaxError.
Correct example:
count = 0
def update():
global count
count += 1
3. Placement of the nonlocal declaration
nonlocal must also be declared before any related use or assignment of that name in the current function.
Correct example:
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
4. Loop variables and local scope
Python's for loops, if conditional statements, and while loops do not create separate local scopes the way functions do.
def test():
for item in range(3):
pass
print(item)
test()
Output:
2
The loop variable item still belongs to the function's local scope.
However, list comprehensions and other comprehensions have their own iteration variable scope: