Sub topic 3
Local names inside a function
This chapter assumes you can define and call functions, use assignment and print, work with lists, and read a simple traceback. The earlier chapters introduced names, binding, and namespaces. This chapter applies them to the namespace a function creates each time it runs.
What a local name is
A local name is a name that exists only while one call to a function is running. Python creates it inside that call and discards it when the call ends. Code outside the function cannot see it.
def area(width, height):
result = width * height
return result
print(area(3, 4))
try:
print(result)
except NameError as error:
print("NameError:", error)
# Output:
# 12
# NameError: name 'result' is not definedHere width, height, and result are all local to area. The module-level print(result) fails because no result exists outside the call.
Each call gets its own namespace
A function definition is a recipe. Each call builds a fresh local namespace, binds the arguments to the parameter names, and runs the body. When the function returns, that namespace is normally released.
Two calls never share local names, even for the same function. The clearest case is recursion, where one call is still running while another begins.
def countdown(n):
label = f"level {n}"
if n > 0:
countdown(n - 1)
print(label)
countdown(2)
# Output:
# level 0
# level 1
# level 2Each of the three calls has its own n and its own label. The inner call setting label to "level 0" does not touch the outer call's label. That is why the outer calls still print level 1 and level 2 afterwards.
What creates a local name
Parameters are local names. So is any name that the function body binds. Binding is broader than the = sign, so it helps to know the full list.
| Statement in the body | Local name it creates |
|---|---|
| `total = 0` | `total` |
| `total += 1` | `total` |
| `for item in data:` | `item` |
| `with open(p) as f:` | `f` |
| `import math` | `math` |
| `def helper():` | `helper` |
| `class Point:` | `Point` |
| `except ValueError as e:` | `e` (removed again when the handler ends) |
| `a, b = pair` | `a` and `b` |
| Function parameters | Each parameter name |
You can inspect the result. Every function object has a code object, and its co_varnames attribute lists the local names, with parameters included.
def demo(data):
total = 0
for item in data:
total += item
import math
def helper():
return 1
return total
print(sorted(demo.__code__.co_varnames))
# Output: ['data', 'helper', 'item', 'math', 'total']The list is sorted here because the order Python stores names in is an implementation detail. co_varnames is a debugging aid, not something to build programs on.
Local status is decided before the function runs
Python does not discover local names while executing. When it compiles the function, it scans the whole body. If a name is bound anywhere in the body, that name is local in the whole body, including lines above the binding.
def pick(flag):
if flag:
value = "set"
return value
print(pick(True))
try:
print(pick(False))
except UnboundLocalError as error:
print("UnboundLocalError:", error)
# Output:
# set
# UnboundLocalError: cannot access local variable 'value' where it is not associated with a valueThe assignment to value sits inside an if, so it does not run when flag is false. Python still treats value as local, so the return cannot fall back to some other value elsewhere. The error wording differs between Python versions. A later chapter covers the case where a global of the same name exists, which is where this rule surprises people most.
Reading the local namespace
The built-in locals() returns a dictionary of the current local names and their values. It is useful for quick inspection.
def show_locals(a, b):
c = a + b
print(sorted(locals()))
print(locals()["c"])
show_locals(1, 2)
# Output:
# ['a', 'b', 'c']
# 3Treat the result as a read-only snapshot. Writing into the dictionary does not create or change real local variables inside a function. If you want a new local name, assign to it in the normal way.
Parameters are locals, and rebinding them stays local
Calling f(value) binds the parameter name to the same object the caller passed. If the function then rebinds the parameter with =, only the local name moves. The caller's name still points to the original object.
def rebind(n):
n = n + 1
return n
value = 5
print(rebind(value))
print(value)
# Output:
# 6
# 5Rebinding is different from mutating. Calling bucket.append(1) on a list parameter changes the shared list object, so the caller sees the change. That distinction has its own chapter. For now, remember that assignment to a local name never changes what the caller's name refers to.
Default values are evaluated once
A default value belongs to the function object, not to a call. Python evaluates it once, when the def statement runs. The parameter is a fresh local on each call, but if its default is a mutable object, every call that uses the default gets that same object.
def append_to(item, bucket=[]):
bucket.append(item)
return bucket
print(append_to(1))
print(append_to(2))
# Output:
# [1]
# [1, 2]The usual fix is to use None as a marker and create the list inside the call, so it really is new each time.
def append_to(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(append_to(1))
print(append_to(2))
# Output:
# [1]
# [2]Locals can outlive the call
The rule that locals vanish on return has one exception. If an inner function uses a local name of its outer function, Python keeps that variable alive for as long as the inner function exists. This is a closure, and it gets its own chapter. For ordinary functions that do not define inner functions, the simple rule holds.
Common mistakes
- Expecting a result to stay behind. Setting a local and then using it after the call raises
NameError. Usereturnto pass values out. - Using a name only bound in one branch. If a name is bound inside an
ifor loop that might not run, give it a value before the branch or make sure every path binds it. - Reusing a loop variable.
for item in dataleavesitembound to the last element after the loop. Ifdatais empty,itemis never bound, and using it afterwards raisesUnboundLocalError. - Relying on
locals()to assign. Changing the dictionary does not change the variables. - Mutable default arguments. Use
Noneand create the object in the body.
Exercise
Look at this function. Which names are local, and what happens when you call check([])?
def check(values):
for v in values:
last = v
return last
Show answer
The local names are values, v, and last. When values is empty, the loop body never runs, so last is never bound. Because last is bound somewhere in the body, Python treats it as local throughout, and return last raises UnboundLocalError. Fix it by assigning last = None before the loop, or by returning early when values is empty.
Exercise
What do the two print calls output, and why? def bump(n): n = n + 10 x = 1 bump(x) print(x) print("n" in dir())
Show answer
The first print shows 1, and the second shows False. Inside bump, n is a local name. The assignment rebinds only that local name, so the module-level x is unchanged. After the call the local namespace is discarded, so no module-level name n exists. dir() with no arguments lists the module-level names here, and n is not among them.