Middle
How is variable scope considered when searching for a variable in Python?
sobes.tech AI
Answer from AI
In Python, variable lookup is performed according to the LEGB rule.
- Local (L): Checked in the current function or method.
- Enclosing Function Locals (E): Checked in the scope of the enclosing function (for nested functions).
- Global (G): Checked in the module where the code resides.
- Built-in (B): Checked in Python's built-in scope (functions like
len,print, etc.).
The interpreter searches for the variable name sequentially in these scopes, starting from the local. Once the name is found, the search stops. If the name is not found in any scope, a NameError is raised.
# Global scope
x = 10
def outer_function():
# Enclosing scope
y = 20
def inner_function():
# Local scope
z = 30
print(x) # Finds x in Global scope
print(y) # Finds y in Enclosing scope
print(z) # Finds z in Local scope
# print(non_existent) # Will raise NameError
inner_function()
outer_function()
Using the keywords global and nonlocal allows changing the lookup and assignment behavior:
global: Allows modifying a variable in the global scope from within a local scope.nonlocal: Allows modifying a variable in the enclosing scope (but not global) from a nested function.
# Global scope
a = 5
def func_global():
global a # Indicates that we are working with the global variable a
a = 15 # Modifies the global variable
print(f"Inside func_global: a = {a}")
def func_nonlocal():
b = 25 # Enclosing scope
def inner_func_nonlocal():
nonlocal b # Indicates that we are working with the variable b from the enclosing scope
b = 35 # Changes the variable b in the enclosing scope
print(f"Inside inner_func_nonlocal: b = {b}")
inner_func_nonlocal()
print(f"Inside func_nonlocal: b = {b}")
func_global()
print(f"Outside: a = {a}")
func_nonlocal()