Concepts and theorems · Intermediate

Closures: following the environment a function retains

Trace the environment associated with a function, using independent counters, shared bindings and explicit snapshots to explain capture behavior.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. A function body does not determine everything
  2. Draw which state each counter reaches
  3. Separate creation time from invocation time
  4. A retained reference is not a deep copy
  5. Consider retained lifetime as a design choice
  6. Exercise: count environments separately from code
  7. Ask Logeia about this articleCheck your understanding

A function body does not determine everything

A closure can be understood as a function together with the environment needed to resolve names outside that function. A counter factory can return an inner function that increments a count, and that returned function can still access the count after the factory call has finished. The end of the outer call does not necessarily make every referenced value disappear. However, saying that a function saves values is too vague. Distinguish referring to a binding, retaining a value chosen at one moment, and sharing a reference to a mutable object. Capture rules differ between languages, so the general environment model must be kept separate from the specific Python behavior demonstrated in the accompanying experiment.

Draw which state each counter reaches

A design can create separate counts for separate calls to make_counter(0) and make_counter(10). Calling the first returned function twice and the second once produces one, two and eleven. The function code can be identical while the associated environments differ. Conversely, two functions created by one factory call can both reference the same count, so a change through one is visible through the other. Merely counting the number of closure objects does not distinguish those cases. Draw arrows from each function to the particular binding it uses. The relevant question is which state is shared, not whether the source contains two function definitions or two variable names. Functions and state cells need not have a one-to-one relationship.

Separate creation time from invocation time

In Python, creating three functions that read a loop variable i does not necessarily create three snapshots containing zero, one and two. If the functions refer to the same binding, they read its value when later invoked. Three function creations are not evidence that three integer values were copied at those moments. This distinction matters when registering callbacks for buttons or asynchronous work: all callbacks acting on the final target suggests checking when an outer name is resolved. The Python result is not a universal rule for visually similar source in every language. Block scope, binding creation and capture modes differ. Confirm the chosen language’s rules before transferring either the expected output or the proposed repair to another runtime.

A retained reference is not a deep copy

A Python default argument can retain the integer selected when a function is created, giving the familiar zero, one and two behavior in the loop example. That technique is not a general deep-copy mechanism. If the retained object is a list, the function still refers to that list; appending to the same object later can change what the function observes. Retaining a reference and cloning all reachable data are different operations. Decide explicitly whether a snapshot is required and what it should contain. Also keep the Python rule about when default arguments are evaluated separate from the general definition of a closure. A useful explanation names both the technique and the precise binding or object whose relationship changed.

Consider retained lifetime as a design choice

A closure that retains a path to a large object can keep that object reachable while the function remains in use. Returning from the outer function does not establish that all of its data was released. An unnecessary event registration can therefore retain more memory than intended. Possible design changes include capturing only required data, unregistering callbacks and making the owner of state explicit. Unregistering also does not automatically establish that no previously started work is running; cancellation and completion have separate contracts. Closures are not synonymous with leaks. They are useful precisely because they can retain required state, but the intended lifetime and referenced objects should be visible in the design, including in a garbage-collected runtime.

Exercise: count environments separately from code

Create two counters with initial value zero, call the first three times, then call the second once. The expected sequence is one, two, three, one: shared implementation code does not imply shared counter state. Next retain a list as a default argument of a function returning its length, then append one item through another reference to that list. Observing length one shows that the function did not receive an independent copy of the original empty list. Draw these cases differently: separate state bindings for the counters, but two arrows to the same list object in the second case. The companion experiment checks the actual outputs. Understanding which relationship must change to obtain another result is more useful than memorizing a closure puzzle.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Build your CS foundations · STEP 19

Choose a learning path