Closures Built in a Loop

A closure can retain access to a binding whose value changes. Several closures created in a loop may therefore observe one later value.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Trace three callbacks
  2. Capture the intended observation

Trace three callbacks

In Python, three lambdas reading the same loop variable after a typical loop over 0, 1, 2 can all return 2. The name was read when each callback ran. Lexical lookup determines which binding is used.

Capture the intended observation

A factory called once per iteration binds its own parameter, yielding callbacks returning 0, 1, and 2. Test them only after the loop to expose the difference. See returning a closed-over function.[1]

References

  1. Python Software Foundation, Functional Programming HOWTO ↩