Experiments and implementations · Intermediate

Observe closure bindings, captured values and shared objects

Run independent counters, loop callbacks, default arguments and a mutable list to distinguish retained bindings from independent object copies.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Predict three distinct relationships
  2. Run under explicit Python rules
  3. Separate factory calls create separate counter state
  4. Read loop bindings after creation finishes
  5. Inspect all four outputs
  6. Choose a repair from the sharing requirement
  7. Exercise: override an argument and change an object
  8. Ask Logeia about this articleCheck your understanding

Predict three distinct relationships

This experiment separates three questions: whether separate function creations provide independent state, when an outer variable is read, and whether retaining a value creates an independent copy. Combining all of them in one complicated example would make a surprising output hard to explain. We use two counters, three loop-created callbacks and one list-retaining function as separate cases. Each is short Python code, but they expose different relationships often hidden behind the word capture. Before running the program, predict the printed values and draw arrows from functions to the bindings or objects they use. Seeing three function objects in source does not establish that three independent state cells exist. The goal is to explain both the values and the reference relationships producing them.

Run under explicit Python rules

Save the complete program as capture.py and execute it with Python 3.12 or a compatible later version. No dependency installation or network connection is needed. The observed results follow Python’s name-resolution and default-argument rules; they are not a promise about similarly shaped C++ or JavaScript source. Record the interpreter version, and check another language’s own scope and capture rules before constructing a comparison. Prefer running the independent file over entering fragments into a long-lived interactive session. Old bindings named i or value would add irrelevant conditions to an experiment about where names resolve. Creating every object and counter inside the program makes the starting state reproducible across runs.

Separate factory calls create separate counter state

Each call to make_counter creates a local binding value and returns an inner function that increments it. The nonlocal declaration selects that enclosing binding instead of creating a new inner local variable. The functions a and b come from separate factory calls with starting values zero and ten. Calling a twice and b once produces the stored list one, two and eleven. Calls to a do not increment b. Results are saved before printing, so observation does not accidentally invoke either counter again. That detail matters whenever reading a result is itself a state-changing operation. Separate the action that changes state from the stored observation used for comparison so that adding diagnostic output does not silently alter the experiment.

Read loop bindings after creation finishes

The three functions in late read the comprehension variable i when later invoked. Because all are invoked after construction has finished, they each return its final value, two. The early functions instead receive a default argument selected during each function creation and are called without overriding that argument, producing zero, one and two. This is not a defect unique to lambda notation. The difference concerns which binding or argument supplies a value and when that value is selected. Ordinary function definitions can require the same reasoning. Invocation order is also part of the setup: constructing every function before calling any is different from immediately calling each function inside the creation loop. Explain the schedule as well as the source syntax when comparing the outputs.

Inspect all four outputs

The output contains counter values one, two and eleven; late callback values two, two and two; early callback values zero, one and two; and finally list length one. Assertions check those observations before printing. In the last case a default argument retains a reference to box, after which another reference appends item to that same list. The empty list was not deep-copied when the function was created, so size observes length one. The integer loop example does not justify claiming that no later change can ever be seen through a default argument. Distinguish numeric values, variable bindings and object references. If output differs, check whether added diagnostics invoked a state-changing function again before changing the explanation to fit the new result.

python
def make_counter(start):
    value = start
    def next_value():
        nonlocal value
        value += 1
        return value
    return next_value

a, b = make_counter(0), make_counter(10)
counters = [a(), a(), b()]
assert counters == [1, 2, 11]
late = [lambda: i for i in range(3)]
early = [lambda i=i: i for i in range(3)]
late_values = [f() for f in late]
early_values = [f() for f in early]
assert late_values == [2, 2, 2]
assert early_values == [0, 1, 2]
box = []
size = lambda box=box: len(box)
box.append('item')
assert size() == 1
print(counters, late_values, early_values, size())

Choose a repair from the sharing requirement

If each button must retain a separate number, explicitly passing that number at function creation is one possible design. If every button should read the latest shared configuration, later access to a common object may be intentional. Copying everything is therefore not a universal repair. Decide which state must be independent and which must remain shared. For mutable data, determine whether a shallow copy suffices or whether nested objects also require separation. Copies have costs and can change identity relationships, so indiscriminate deep copying is not a substitute for a requirement. Asynchronous applications also need lifetime and completion rules. This experiment uses sequential calls and provides no evidence about concurrent access safety.

Exercise: override an argument and change an object

Call the second early function first without an argument and then with the explicit argument ninety-nine. The worked answers are one and ninety-nine. A default argument supplies a value when omitted; it is not an immutable constant that ignores caller input. Next append a second item to box and predict size: it returns two because the same list object is retained. Finally predict one further call to each counter. The next a result is three, while the next b result is twelve. Link each answer to its particular state update rather than treating capture as one undifferentiated mechanism. Save the file for comparison; no external process or data store needs cleanup. Real callback registration and removal require the contract of the actual API used.

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