Sub topic 3
Enclosing Scopes and Closures
Assume you know how to define and call functions, use lists, assign values, and read a simple traceback. This chapter focuses on nested functions and common scope mistakes.
Enclosing scopes and closures
An enclosing scope belongs to an outer function. A nested function can read names from that scope. When the nested function remembers those names after the outer function returns, the result is a closure.
def make_greeting(name):
def greet():
return "Hello, " + name
return greet
message = make_greeting("Ava")
print(message())
# Hello, AvaThe function greet keeps access to name even after make_greeting has finished.
Rebinding an enclosing name with nonlocal
Reading an enclosing name works automatically. Reassigning it requires nonlocal.
def make_counter():
total = 0
def add(amount):
nonlocal total
total += amount
return total
return add
counter = make_counter()
print(counter(2))
print(counter(3))
# 2
# 5Use nonlocal when a closure needs private, changing state. For simple calculations, passing values and returning results is usually clearer.
Built-in names and accidental shadowing
Python provides built-in names such as list, sum, and id. A local or module-level name with the same spelling shadows the built-in.
list = [1, 2, 3]
print(list("abc"))
# TypeError: 'list' object is not callableChoose descriptive names such as values or items instead.
Late binding in closures
Closures look up free variables when called, not when created. This is called late binding.
functions = [lambda: i for i in range(3)]
print([function() for function in functions])
# [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([function() for function in fixed])
# [0, 1, 2]The default argument stores each current value.
Class bodies and comprehensions
A method does not search the class body as an enclosing function scope. Use self.size or the class name.
class Box:
size = 10
def get_size(self):
return self.size
print(Box().get_size())
# 10Comprehensions have their own scope. Their loop variable does not replace a name outside the comprehension.
value = "outside"
items = [value for value in range(3)]
print(value)
# outsideWriting code that avoids scope pitfalls
- Prefer local variables and function arguments.
- Return new values instead of changing global state.
- Use nonlocal only for intentional closure state.
- Avoid names that shadow built-ins.
- Bind loop values explicitly when creating closures.
- Access class data through self or the class name.
Exercise
Why does the first list of functions return three 2 values, and how does the default argument fix it?
Show answer
Each function looks up i when called, after the loop ends. The default argument stores the value of i when each function is created.