In Python, functions created inside loops look up variables in the enclosing scope when called, NOT when created. Thus, all closures bind to the same variable `i` at its final value!
In Python, functions created inside loops look up variables in the enclosing scope when called, NOT when created. Thus, all closures bind to the same variable `i` at its final value!
The closure fixture creates three lambdas sharing the enclosing variable slot i. The saved final slot value is two; calling each with x equal two produces four. Bars show the first and second saved outputs at one hundred twenty pixels per value unit. Looking up a shared enclosing cell differs from saving an independent value at creation. This page plays authored snapshots, not a live Python interpreter. The mutable default fixture saves one list object in the function default. Its first call appends one, producing a one-item list; the second appends two to the same object, producing two items. Bars use two hundred pixels per item. The full exported steps retain heap IDs and frame references, explaining why a new call does not mean a new default list. This is a supplied trace, not execution of edited Python. The class fixture has two instances named a and b with one shared class attribute tricks. Appending through a changes the list later read through b. Bars show two instances versus one shared class list at two hundred pixels per object. Attribute lookup can fall back to the class, whereas assignment of an instance attribute differs. This is the saved reference example, not measured interpreter allocation or universal interning.