Fix Late Binding in Closure Loops
Core idea
Functions defined in a loop can refer to the same loop variable. When the functions are called later, they read its current value. In a function scope this can be a shared enclosing binding. A default parameter evaluated at definition time can retain each iteration’s value.
def make_readers(): readers = [] for number in range(3): def read(): return number readers.append(read) return readersprint([read() for read in make_readers()])All three functions read the final value of the same enclosing number.
Capture a value using a default
def make_readers(): readers = [] for number in range(3): def read(saved=number): return saved readers.append(read) return readersprint([read() for read in make_readers()])Each definition evaluates its own default. saved is a local parameter when the function runs.
Use a separate enclosing call
def reader_for(number): def read(): return number return readreaders = [reader_for(n) for n in range(3)]print([read() for read in readers])Each call to reader_for creates a distinct enclosing binding for number.
Common mistake
A default stores an object reference, not a deep copy. Capturing a mutable list this way still allows later mutations of that list to be observed.
Practice
Create readers for 10, 20 and 30. Predict the shared-binding result and then fix it using each technique.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Avoid late binding surprises
Check your understanding of late binding.
What is printed?
def build(): funcs = [] for n in [3, 4]: def read(): return n funcs.append(read) return funcsprint([f() for f in build()])What is printed?
def build(): funcs = [] for n in [3, 4]: def read(saved=n): return saved funcs.append(read) return funcsprint([f() for f in build()])What is printed?
def create(n): def read(): return n return reada = create(5)b = create(6)print(a(), b())Does a default parameter automatically deep-copy a list?