
Table of Contents(目次)
- 1. What Is a Scope? Understanding Variable Visibility in Python
- 2. The Four Levels of Scope (LEGB Rule) and Search Order
- 3. The Difference Between Global and Local Variables
- 4. Updating Global Variables with the global Statement
- 5. Using nonlocal and Nested Functions to Modify Variables
- 6. Scope and Variable Lifetime
- 7. Writing Clean Functions with Scope Awareness
1. What Is a Scope? Understanding Variable Visibility in Python
Scope defines the rule that determines where a variable can be "seen" and "used." In Python, the area where a variable can be referenced depends on where it is defined.
By understanding scope, you can prevent unintended errors and write cleaner, safer code.
x = 10 # Global scope (accessible from anywhere)
def sample():
y = 5 # Local scope (valid only inside the function)
print(x) # OK
print(y) # OK
sample()
print(x) # OK
print(y) # Error (y is not visible outside the function)
In the example above, x is a global variable, accessible from anywhere. On the other hand, y is a local variable defined inside the function and cannot be accessed outside it.
2. The Four Levels of Scope (LEGB Rule) and Search Order
Python follows a specific rule to search for variables called the LEGB Rule.
LEGB Rule:
- L (Local): The local scope inside a function
- E (Enclosing): The scope of the outer function when functions are nested
- G (Global): The global scope of the entire module
- B (Built-in): The built-in scope of Python (e.g.,
len,print)
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(f'Line 7 x = {x}') # local
inner()
print(f'Line 9 x = {x}') # enclosing
outer()
print(f'Line 12 x = {x}') # global
Line 7 x = local
Line 9 x = enclosing
Line 12 x = global
Python searches for variables in this order: L → E → G → B.
3. The Difference Between Global and Local Variables
A global variable is accessible throughout the entire module, while a local variable can only be used inside a function.
count = 0 # Global variable
def add():
count = 10 # Local variable (a different one)
print('Inside function:', count)
add()
print('Outside function:', count)
Inside function: 10
Outside function: 0
In this case, the count defined inside the function is a separate variable from the global count. The global value remains unchanged.
If a line like count = 10 exists inside a function, Python treats count within that function as a local variable. Therefore, attempting to reference count before it is initialized as a local variable will raise an error.
count = 0 # Global variable
def add():
print('Inside function:', count) # Error: trying to access before local initialization
count = 10 # Local variable (different one)
add()
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
As shown in the first example, you can still reference the global variable as long as the function does not assign or modify a variable with the same name inside its body.
x = 10 # Global
def sample():
print(x) # You can reference x as long as it is not modified inside the function
sample()
4. Updating Global Variables with the global Statement
If you want to modify a global variable from inside a function, use the global statement.
count = 0
def add():
global count
count += 1
print('Inside function:', count)
add()
print('Outside function:', count)
Inside function: 1
Outside function: 1
By declaring global count, the variable count inside the function refers to the global one, allowing both modification and access.
5. Using nonlocal and Nested Functions to Modify Variables
In nested functions (functions defined inside other functions), you can modify a variable from the outer function using nonlocal.
def outer():
x = 0
def inner():
nonlocal x
x += 1
print('inner:', x)
inner()
print('outer:', x)
outer()
inner: 1
outer: 1
By using nonlocal x, the inner() function can modify the variable x defined in outer().
6. Scope and Variable Lifetime
Scope and a variable’s lifetime are closely related. A local variable is created each time a function runs and is destroyed when the function ends.
def counter():
x = 0
x += 1
print(x)
counter()
counter()
1
1
In this example, the variable x is reset each time. If you want to retain a value between function calls, consider one of the following approaches:
- Use a global variable
- Use a class or closure mechanism
- Use return values and arguments to pass data
7. Writing Clean Functions with Scope Awareness
By understanding scope, you can design clean code that doesn’t depend on global variables. The following example shows how to maintain state without using globals.
def create_counter():
count = 0
def add():
nonlocal count
count += 1
return count
return add
counter = create_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
By combining nonlocal with a closure, you can manage state without relying on global variables. Understanding scope enables you to design maintainable, modular functions.
Closures will be covered in detail in a dedicated lecture.






