Sub topic 7
Where function variables live: local scope
This chapter assumes you can define a function with def, pass it arguments, and use return. It covers which variables a function can see, which it creates, and why assigning to a name changes what that name means inside the function.
Parameters and variables belong to one call
A name created inside a function body is a local variable. Parameters are local variables too: Python creates them when the call starts and binds them to the arguments. When the call ends, all of them are discarded.
def total_price(price, quantity):
subtotal = price * quantity
return subtotal
print(total_price(4, 3)) # 12
try:
print(subtotal)
except NameError as error:
print(error) # name 'subtotal' is not definedprice, quantity and subtotal exist only while total_price runs. Code outside the function cannot see them.
Each call gets its own fresh set of locals. Nothing carries over from one call to the next:
def counter_demo():
count = 0
count += 1
return count
print(counter_demo()) # 1
print(counter_demo()) # 1A function that must remember something between calls needs a different mechanism: a returned value that the caller passes back in, an object, or a closure (see the end of this chapter). Local variables cannot do it.
The scope lookup order
When Python meets a name inside a function, it searches four places in a fixed order, known as LEGB:
- Local: names assigned in the current function, including parameters.
- Enclosing: names in any function that contains this one.
- Global: names assigned at the top level of the module.
- Built-in: names such as
print,lenandmax.
The first match wins. If no scope has the name, Python raises NameError.
Python never searches inward. An outer scope cannot see the locals of a function it calls.
Reading a global from inside a function
A function can read a module-level name without any declaration, because the lookup falls through to the global scope:
TAX_RATE = 0.25
def with_tax(price):
return price * (1 + TAX_RATE)
print(with_tax(100)) # 125.0Reading globals is acceptable for constants such as TAX_RATE. Treat it with suspicion when the global is data that changes. The function's result then depends on something that is not in its parameter list, which makes it harder to test and reason about. Passing the value as a parameter is usually cleaner.
Assignment creates a local name
A function's local names are decided before the function runs. If a name is assigned anywhere in the body, Python treats it as local for the whole body, even on lines that come before the assignment. This is the source of the most common scope error.
total = 0
def add_bad(n):
total = total + n # total is local here, and has no value yet
return total
try:
add_bad(5)
except UnboundLocalError as error:
print("UnboundLocalError:", error)The right-hand side reads total. Because the line also assigns total, Python has already marked it local, and the local has no value yet. The global total is not consulted. The exact wording of the message varies between Python versions, but the exception type is UnboundLocalError.
The same rule explains a quieter bug. Assignment creates a new local that hides the global of the same name. This is called shadowing:
name = "global"
def show():
name = "local"
print(name)
show() # local
print(name) # globalThe function did not change the module-level name. It created a separate variable that happens to share the name. A parameter shadows in the same way: if a function has a parameter called total, the global total is invisible inside it.
Scope is per function, not per block
Python has no block scope for if, for or while. A variable assigned inside one of those blocks belongs to the whole function:
def first_even(numbers):
for n in numbers:
if n % 2 == 0:
found = n
break
return found
print(first_even([3, 5, 8, 9])) # 8
try:
first_even([1, 3, 5])
except UnboundLocalError as error:
print("no even number found")found and n are both visible after the loop ends, which is convenient. The danger is the path where the assignment never ran. Here found is local but has no value, so return found fails. Initialize the variable before the loop (for example found = None) when some paths might skip the assignment.
Comprehensions are the exception: the loop variable in [x * 2 for x in values] is local to the comprehension and does not leak into the function.
Changing a global with `global`
To rebind a module-level name from inside a function, declare it with global:
hits = 0
def record_hit():
global hits
hits += 1
record_hit()
record_hit()
print(hits) # 2The global statement tells Python that hits in this function refers to the module-level name, so assignment rebinds that name. Without the statement, hits += 1 would raise UnboundLocalError.
The same function written without global:
def record_hit(hits):
return hits + 1
hits = 0
hits = record_hit(hits)
hits = record_hit(hits)
print(hits) # 2Every input and output is now visible in the signature.
Nested functions and `nonlocal`
A function defined inside another function can read the outer function's locals through the enclosing scope. To rebind one of them, it uses nonlocal, which works like global but targets the nearest enclosing function:
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2count outlives the call to make_counter because increment still refers to it. This is a closure. It is the main case where a local variable survives past its call, and each call to make_counter creates an independent count. Closures are a larger topic. For this chapter, remember only that nonlocal exists and that it is rarely needed in everyday functions.
Quick reference
| Situation | What happens | Fix |
|---|---|---|
| Read a name that exists only at module level | Works through the global lookup | None needed, but prefer a parameter for changing data |
| Assign to a name that is also global | Creates a new local that shadows the global | Use a different name, or declare `global` if rebinding is intended |
| Read a name before assigning it in the same function | `UnboundLocalError` | Initialize it first, or pass it in as a parameter |
| Use a local after the function returns | `NameError` | Return the value |
| Assign inside `if` or `for`, use it after | Works only if that path ran | Initialize before the block |
| Rebind a variable of an enclosing function | Creates a new local | Declare `nonlocal` |
Diagnosing scope errors
Two habits catch most scope bugs:
- Read the error type.
NameErrormeans no scope has the name, which is usually a typo or a variable you expected to survive from another function.UnboundLocalErrormeans the name is local to this function but unassigned at that point, so look for an assignment elsewhere in the same body. - Check the neighbors of the failing line. A single
+=,=orfortarget anywhere in the function makes the name local everywhere in it.
def debug_demo(a, b):
c = a + b
print(locals()) # {'a': 1, 'b': 2, 'c': 3}
return c
debug_demo(1, 2)The next chapter builds on this. Locals are separate names, but a name and the object it refers to are separate things, and that affects what happens when you pass a list or dictionary into a function.
Exercise
The code below raises an error. Which error, why, and what is the smallest change that makes it print 15? balance = 10 def deposit(amount): balance = balance + amount return balance print(deposit(5))
Show answer
It raises UnboundLocalError. Because balance is assigned inside deposit, Python treats it as a local variable for the whole function, so the read on the right-hand side finds a local with no value. The smallest fix that keeps the design clean is to give the parameter-based version a different local name, for example new_balance = balance + amount; return new_balance, which reads the global and creates a distinct local. Declaring global balance also prints 15, but it rebinds the global and is the weaker design.
Exercise
What does this program print, and why? x = "outer" def f(): x = "inner" def g(): print(x) g() f() print(x)
Show answer
It prints "inner" and then "outer". Inside g, the name x is not local, so the lookup moves to the enclosing scope, which is f, and finds "inner". The assignment in f created a local that shadows the global, so the module-level x is never changed and the last line prints "outer".