Python Scope
The scope of a variable is the part of the program where that name can be seen and used. Scope rules explain why a variable created inside a function "disappears" afterwards, and why changing a global from inside a function needs a special keyword.
Local scope
A variable assigned inside a function is local to that function. It is created when the function runs and forgotten when it returns:
def make_greeting():
message = "Hello from inside"
return message
print(make_greeting())
try:
print(message)
except NameError as err:
print("Error:", err)Hello from inside
Error: name 'message' is not defined
Every call gets fresh local variables, so two functions can use the same local name without interfering.
Global scope
A variable created at the top level of a file is global. Functions can read it:
TAX_RATE = 0.08
def price_with_tax(price):
return round(price * (1 + TAX_RATE), 2)
print(price_with_tax(50))54.0
Assigning creates a local
Here is the rule that surprises people: if a function assigns to a name anywhere in its body, that name is local throughout the whole function — even if a global with the same name exists:
counter = 0
def increment_wrong():
counter = 1 # creates a NEW local variable
return counter
increment_wrong()
print(counter) # the global is unchanged
def increment_broken():
try:
counter += 1 # reads the local before it exists
except UnboundLocalError as err:
print(type(err).__name__)
increment_broken()0
UnboundLocalError
The global keyword
To rebind a global variable from inside a function, declare it with global:
visits = 0
def record_visit():
global visits
visits += 1
record_visit()
record_visit()
print(visits)2
Tip: Use
globalsparingly. Functions that read their inputs from parameters and hand back results withreturnare much easier to test and reuse.
Enclosing scope and nonlocal
When a function is defined inside another function, the inner one can read the outer one's variables. To rebind them, use nonlocal:
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
tick = make_counter()
print(tick(), tick(), tick())
other = make_counter() # an independent counter
print(other())1 2 3
1
Each call of make_counter creates a new count, and the returned step function keeps access to it — a closure.
The LEGB rule
When Python looks up a name, it searches four scopes in order and uses the first match:
| Order | Scope | Contains |
|---|---|---|
| L | Local | names assigned in the current function |
| E | Enclosing | names in any outer function(s) |
| G | Global | names at the top level of the module |
| B | Built-in | print, len, range, … |
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print("inner sees:", x)
inner()
print("outer sees:", x)
outer()
print("module sees:", x)inner sees: local
outer sees: enclosing
module sees: global
Don't shadow built-ins
Because built-ins are searched last, a global or local with the same name hides them:
list = [1, 2, 3] # hides the built-in list type
try:
list("abc")
except TypeError as err:
print("Error:", err)
del list # remove our name; the built-in is visible again
print(list("abc"))Error: 'list' object is not callable
['a', 'b', 'c']
Avoid naming variables list, dict, str, sum, max, id or input.
Note: Loops and
ifblocks do not create a new scope in Python. A variable assigned inside aforloop is still available after the loop ends.
Test yourself
Which keyword lets a function rebind a variable defined at module level?
- nonlocal
- global
- outer
- static
In what order does Python search scopes for a name?
- Global, Local, Built-in, Enclosing
- Local, Enclosing, Global, Built-in
- Built-in, Global, Enclosing, Local
- Local, Global, Enclosing, Built-in
Does a for loop create its own variable scope?
- Yes, always
- No, loop variables live in the surrounding scope
- Only inside functions
- Only for range()