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

Taught in

References

Certification courses