Scope
Scope decides where a variable is visible.
Syntax
global nameScope determines where a variable can be used.
- Local — created inside a function; only visible there.
- Global — created at the top level of a file; visible everywhere.
A function can read global variables, but to reassign one it must declare global name first. Python looks up names using the LEGB rule: Local, Enclosing, Global, Built-in.
Example
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
print(counter)
# Output:
# 2When to use it
- A configuration loader uses a module-level global variable to hold settings available everywhere.
- A counter function uses 'nonlocal' to modify an enclosing function's variable inside a closure.
- A function declares a local variable with the same name as a global to avoid unintended side-effects.
More examples
Local vs global scope
Shows that local_val exists only inside the function while count is visible globally.
count = 0 # global
def increment():
local_val = 10 # local only
print('Inside:', local_val)
increment()
print('Outside:', count)
# print(local_val) # NameError: not accessible hereModify a global variable
Uses the 'global' keyword to allow a function to modify a module-level variable.
visits = 0
def record_visit():
global visits
visits += 1
record_visit()
record_visit()
print(visits) # 2nonlocal in a closure
Uses 'nonlocal' so the inner increment() function can update the enclosing function's variable n.
def make_counter():
n = 0
def increment():
nonlocal n
n += 1
return n
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
Discussion