Sub topic 14
Writing Code That Avoids Scope Pitfalls
This chapter assumes you know how to define and call functions, read a traceback, and use lists. It also assumes you have seen the LEGB lookup rule (local, enclosing, global, built-in) and the global and nonlocal statements. Here we turn those rules into habits that keep scope bugs out of your code.
Why scope bugs are worth designing against
Scope errors are rarely hard to fix once you see them. They are hard to notice. A function that quietly reads a global works today and breaks when someone renames that global. A shadowed built-in fails far from the line that caused it. A closure built in a loop returns the wrong value only when called later.
Most of these bugs share one cause: a function depends on names it did not receive as arguments and does not return as results. The practices below shrink that hidden dependency.
Practice 1: Pass data in and return data out
A function that takes its inputs as parameters and returns its outputs does not need global at all. Compare these two versions of a counter.
count = 0
def increment_global():
global count
count += 1
increment_global()
increment_global()
print(count)
# Output: 2def increment(count):
return count + 1
count = 0
count = increment(count)
count = increment(count)
print(count)
# Output: 2The second version has several advantages:
- You can read the function alone and know everything it touches.
- You can test it with any value, without first setting up a module-level variable.
- Two callers cannot interfere with each other through shared state.
The rebinding happens at the call site, where it is visible.
Practice 2: Keep module-level state small and named clearly
Some global state is legitimate. Constants are the clearest case. Python has no enforced constants, so the convention is uppercase names that signal "do not rebind".
MAX_RETRIES = 3
TIMEOUT_SECONDS = 2.5
def should_retry(attempt):
return attempt < MAX_RETRIES
print(should_retry(1))
print(should_retry(3))
# Output:
# True
# FalseReading a global constant inside a function is safe. The lookup falls through from local to global scope, and nothing is rebound. The risk lies in globals that change while the program runs, because any function can alter them and you cannot tell which one did.
When you need changing state shared between functions, there are better containers than a bare global.
Practice 3: Prefer a class or closure over global state
If several functions share state that changes, group them. A class makes the state explicit as attributes.
class Counter:
def __init__(self):
self.total = 0
def add(self, n):
self.total += n
return self.total
counter = Counter()
print(counter.add(2))
print(counter.add(3))
# Output:
# 2
# 5Here self.total += n rebinds an attribute of the object, not a name in any enclosing scope, so neither global nor nonlocal is needed. Each Counter() has its own total, so you can have as many independent counters as you like. A global would give you exactly one.
A closure with nonlocal gives similar isolation when you need only one small function:
def make_counter():
total = 0
def add(n):
nonlocal total
total += n
return total
return add
a = make_counter()
b = make_counter()
print(a(2))
print(a(3))
print(b(10))
# Output:
# 2
# 5
# 10Each call to make_counter creates a separate total, so a and b do not share state.
The table below summarizes when each tool fits.
| Situation | Better choice |
|---|---|
| Value is only needed for one computation | Parameter and return value |
| Fixed configuration read by many functions | Uppercase module constant |
| Changing state with several related operations | Class with attributes |
| One small function that remembers state | Closure with `nonlocal` |
| Rebinding a module-level name from a function | `global`, as a last resort |
Practice 4: Know whether you mutate or rebind
The global statement is needed only to rebind a name. Calling a method that changes an object does not rebind anything.
items = []
def add_item(value):
items.append(value)
add_item(1)
add_item(2)
print(items)
# Output: [1, 2]This works without global, but it is still hidden shared state. Anyone reading add_item(1) at a call site cannot tell that a module-level list changed. The same is true of mutable default arguments and of lists passed in and modified in place. Make the intent plain in one of two ways:
- Return a new object and let the caller rebind:
items = with_item(items, 1). - If the function does mutate its argument, say so in its name or docstring, for example
append_item(items, value).
Be careful with augmented assignment. For a list, items += [3] mutates in place, but for an integer or a string x += 1 rebinds. Inside a function, both forms make the name local because both contain an assignment. That is why count += 1 raised UnboundLocalError earlier in this tutorial, while items.append(3) did not.
Practice 5: Do not shadow built-ins
Names such as list, dict, str, id, type, max, sum, input, and file-like words are easy to reuse by accident. Rebinding one at module level hides the built-in for the whole module.
list = [1, 2, 3]
print(list("abc"))
# TypeError: 'list' object is not callableThe failure appears at the call, which may be many lines away from the assignment. To avoid this:
- Choose descriptive names:
numbers,user_id,kind,total. - If a short name is natural, add a trailing underscore:
type_,id_. - Turn on a linter that reports shadowed built-ins. Ruff (rule
A001,A002) and flake8-builtins do this.
If you have already shadowed a built-in in an interactive session, del list removes your binding and the built-in becomes visible again. In a script, rename the variable instead.
Practice 6: Bind loop variables when creating closures
Closures look up names when they run, not when they are created. A function created in a loop sees the final value of the loop variable.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
# Output: [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
# Output: [0, 1, 2]A default argument is evaluated once, when the function is defined, so i=i captures the current value. An alternative is functools.partial, which stores the argument explicitly and avoids the risk of a caller overriding the default:
from functools import partial
def show(i):
return i
bound = [partial(show, i) for i in range(3)]
print([f() for f in bound])
# Output: [0, 1, 2]Practice 7: Do not rely on class-body names inside methods
Names defined in a class body are not in the scope that methods search. A method must reach them through self or the class name.
class Box:
size = 10
def get_size(self):
return self.size
print(Box().get_size())
# Output: 10Using self.size also lets a subclass or an instance override the value, which Box.size would prevent. Choose self.size by default, and Box.size when you specifically want the class-level value.
A checklist for reviewing scope in your own code
The diagram shows the order of questions to ask when a function needs to work with a name that lives outside it.
Before you commit a function, check these points:
- Does every name it uses come from a parameter, a local assignment, an import, or a clearly named constant?
- Does any
globalornonlocalappear? If so, is there a reason it cannot be a parameter, a return value, or an attribute? - Does any variable name match a built-in?
- Are any functions created in a loop that capture the loop variable?
- Does any method use a bare name that is defined in the class body?
Common mistakes when applying these practices
- Declaring
globalfor names you only read. It is harmless but misleading, because it tells readers that the function rebinds the name. - Using
globalto avoid passing arguments through several layers. This trades a short-term convenience for state that is hard to test. Consider grouping the values in a small object or dictionary and passing that one object. - Putting
globalafter the name is used. Python raises aSyntaxErrorif a name is used or assigned before itsglobaldeclaration in the same function. Place the declaration at the top. - Mutable module state in tests. A global changed by one test leaks into the next. Keep state in objects that each test creates.
- Importing a name and then rebinding it elsewhere. After
from config import limit, assigningconfig.limit = 5does not change your locallimit, because the two names are separate bindings to the same original object.
Exercise
The function below is meant to keep a running total across calls, but it fails. Explain why, then rewrite it twice: once as a closure and once as a class. Both versions should print 4 and then 9 for the calls add(4) and add(5).
total = 0
def add(n):
total += n
return total
Show answer
Because total += n is an assignment, Python makes total local to add for the whole function body. Reading it before it has a value raises UnboundLocalError. Closure version: define def make_adder(): with total = 0, an inner def add(n): that declares nonlocal total, does total += n, and returns total, then have make_adder return add. Class version: class Adder: with __init__ setting self.total = 0 and a method add(self, n) doing self.total += n; return self.total. Calling add(4) then add(5) on either version gives 4 and then 9.
Exercise
A teammate writes max = 0 at module level and later calls max(scores) in a function. What happens, and what are two ways to prevent it?
Show answer
The call raises TypeError: 'int' object is not callable, because the module-level name max now refers to the integer 0 and hides the built-in. Prevent it by renaming the variable to something descriptive such as highest, or by using a linter rule that flags shadowed built-ins (for example Ruff's A001).