late binding
Looking a closure's variable up when the function is called rather than when it is created.
In more detail
Functions made in a loop that use the loop variable all see its final value, because they read it only when called. A default argument such as lambda i=i: i captures the current value instead, because defaults are evaluated when the function is defined.
Example
fs = [lambda: i for i in range(3)]
print([f() for f in fs]) # [2, 2, 2]Related terms
- closure — A function bundled with the variables it remembers from the scope where it was created.
- lambda — A small function written inline as an expression, such as lambda x: x * 2, with no name and a single expression as its body.
- loop variable — The name in a for heading that takes each item of the sequence in turn, as item in for item in items.
Taught in
- Closures: Functions That Remember — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep