Sub topic 14
Writing Code That Avoids Scope Pitfalls
This chapter assumes you know the LEGB lookup rule, why assignment inside a function makes a name local, and how global and nonlocal work. It also assumes you can tell rebinding a name from mutating an object. Here you will turn those rules into habits.
Pass values in and return values out
Most scope bugs come from functions that quietly depend on, or change, names outside themselves. A function that takes arguments and returns a result has no such hidden connections.
def increment(count):
return count + 1
count = 0
count = increment(count)
count = increment(count)
print(count)
# Output: 2The caller decides what happens to the result. You can test increment without setting up any global state.
Choose the right tool
Use this flow when a function seems to need to change something outside itself.
Keep module-level names read-only
Module-level names that functions only read are safe. Mark them as constants with uppercase names so readers know not to rebind them.
TAX_RATE = 0.25
def add_tax(price):
return price * (1 + TAX_RATE)
print(add_tax(80))
# Output: 100.0Make mutation visible
A function that calls items.append(value) on a global list needs no global statement. That makes the change easy to miss when you read the code. Passing the list in makes the dependency clear.
def add_item(items, value):
items.append(value)
cart = []
add_item(cart, 1)
add_item(cart, 2)
print(cart)
# Output: [1, 2]Use a class when state grows
A closure with nonlocal suits one small piece of state. When you need several values or several operations, a class is easier to read and extend.
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 is an attribute lookup, so no scope statement is needed.
Do not shadow built-ins
Names such as list, dict, sum, max, id, type, and input live in the built-in scope. Binding one of them at module level hides it for the whole module. Choose descriptive names like numbers, user_id, or kind. A linter such as Ruff or Pylint can flag shadowing for you.
Capture loop variables deliberately
Closures look up a name when they are called, not when they are created. If you build functions in a loop, bind the current value with a default argument.
callbacks = [lambda i=i: i for i in range(3)]
print([f() for f in callbacks])
# Output: [0, 1, 2]Quick checklist
| Situation | Preferred approach |
|---|---|
| Function needs data | Take it as a parameter |
| Function produces data | Return it |
| Shared fixed settings | Uppercase module constants |
| Small private state | Closure with `nonlocal` |
| State plus several operations | Class |
| Functions built in a loop | Bind values with default arguments |
Exercise
This code raises UnboundLocalError. Rewrite it without using global. total = 0 def add(n): total += n add(5) add(7)
Show answer
Pass the value in and return the new one, then rebind it at the call site: total = 0 def add(total, n): return total + n total = add(total, 5) total = add(total, 7) print(total) # 12 This works because add only uses its own local names. The caller rebinds the module-level total.
Exercise
Why is max = 10 at module level risky, even if the program runs without errors at first?
Show answer
It binds the name max in the module's global scope, which hides the built-in max function. Any later call such as max(1, 2) in that module raises TypeError: 'int' object is not callable. Use a name like max_items instead.