Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 17 / FUNCTIONS AND REUSABLE CODE

Closures, scope and late binding

Understand what a nested function remembers and why loop callbacks surprise people.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain a closure retains bindings
  • Apply capture an intended value explicitly
  • Reason about choose stateful abstractions deliberately
01

A closure retains bindings

A closure is a function that still has access to a name from an enclosing function after that enclosing call has finished.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a closure to configure a small operation once and call it later. First understand function calls and local variables: each call gets its own local names.

Words you will see

Binding
A connection between a name and an object.
Enclosing scope
The surrounding function's names, available to its nested function.
Late binding
Reading the current enclosing binding when a function runs, rather than copying its old value.

A retained name is not a photograph

The inner read function uses value without receiving it as an argument. Because value belongs to the enclosing function, Python keeps access to that binding when read escapes through return.

Assigning value = 8 before returning changes what read will see. The earlier integer 3 is not secretly copied into the function. Use an ordinary parameter instead when the caller should supply a new value on every call.

Definition time and call time differ

def read(): builds a function; it does not yet execute return value. The assignment to value happens before reader() finally reads that name, so the printed result is 8.

A missing local name can raise NameError; assigning to a name inside the inner function makes it local unless declared otherwise. Keep dependencies small and visible rather than capturing a whole request object for one field.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. value = 3

    Create the enclosing binding.

  2. value = 8

    Replace its value before the outer call ends.

  3. return read

    Return the function, not the result of calling it.

  4. print(reader())

    Call the escaped function and display 8.

A nested function can use names from its enclosing scope after the outer function returns. That does not mean every value was frozen when the function was created. Python resolves an enclosing binding when the function executes; loop-created callbacks can all observe the final loop value.

Conceptual cause and effect, not a live runtime trace

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. Call outerCreate value in this call's scope.
  2. Return functionThe function keeps access to that scope.
  3. Call innerRead the binding's current value: 8.
Predict before you run

Does reader() return 3 or 8?

Read a retained bindingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Delete the second assignment.

Try: Remove value = 8.

The binding stays 3, so reader prints 3.

Make two readers.

Try: Call make_reader twice and print(reader is make_reader()).

It prints False: each outer call builds a separate function and enclosing scope.

Before you move on

An outer function sets flag to 'new', defines read, then sets flag to 'done' and returns read. What does read() return?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

It returns 'done'. The returned function reads the enclosing flag when called, after the replacement.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Capture an intended value explicitly

A factory gives each callback its own enclosing binding. A default parameter can instead store a chosen reference when the function is defined.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use separate bindings when building callbacks in a loop. A callback is simply a function saved to be called later.

Words you will see

Factory
A function that creates and returns another object or function.
Callback
A function handed to other code for a later call.
Default parameter
An argument value evaluated once when def executes, used when that argument is omitted.

One loop name can surprise all callbacks

The bad list stores three functions, but each function reads the same loop binding i. The loop ends with i equal to 2, so every later call returns 2. Three function objects do not imply three captured loop values.

The good list evaluates i as the default expression for value during each function definition. Calling with no argument reads the saved default reference. This is safe for these integers; a default list would still be a shared mutable object.

Pick the clearest capture

A small factory is often easier to explain when more than one configured value is needed. A default argument is compact but also becomes a parameter that callers can override.

For one fixed argument to an existing function, functools.partial is another option. Do not repair late binding by moving the loop name to global state: that makes sharing wider, not clearer.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. bad = [lambda: i for i in range(3)]

    Build three delayed reads of one loop binding.

  2. good = [lambda value=i: value for i in range(3)]

    Evaluate a default at each iteration.

  3. print([read() for read in good])

    Read the saved defaults in creation order.

A factory creates a fresh enclosing binding for each callback; an immutable default parameter can also capture a loop value at definition time. Use nonlocal when deliberately rebinding an enclosing name, not as a substitute for clear state ownership.

Predict before you run

What does the bad group print?

Compare delayed loop readsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Build four callbacks.

Try: Replace both range(3) calls with range(4).

bad returns four 3s; good returns 0 through 3.

Override a saved default.

Try: Add print(good[0](9)).

It prints 9 because the explicit argument takes precedence over the default.

Before you move on

Two callbacks use defaults value=4 and value=7. What do calls with no arguments return, and can a caller override them?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

They return 4 and 7. A caller can pass a different value because these are ordinary default parameters.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Capture each multiplier

Calling a factory repeatedly creates independent configured functions rather than several readers of one shared loop variable.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a multiplier factory when each saved operation must remember its own factor without exposing a mutable global setting.

Words you will see

Nested function
A function defined inside another function.
Invocation
One particular call of a function.
Captured factor
The enclosing factor binding retained by the returned apply function.

Follow one factory call

multiplier(1) binds factor to 1, creates apply, and returns it without applying it yet. That apply can later multiply any supplied value by 1. multiplier(2) creates a different enclosing factor.

The list comprehension calls the factory for 0, 1 and 2. It stores three returned functions, not three multiplication results. The final comprehension supplies 10 to each saved function.

Know what is shared

The input value belongs to each apply call. The factor belongs to its factory call. Calling functions[1](6) therefore gives 6 without changing the configured factor or the other functions.

An ordinary function multiply(factor, value) is simpler when callers can supply both numbers every time. A callable class is useful if the configured operation needs several named settings or inspection methods.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def apply(value):

    Define the returned operation inside one multiplier call.

  2. return factor * value

    Combine that call's factor with this call's argument.

  3. functions = [multiplier(i) for i in range(3)]

    Create three separate enclosing scopes.

  4. print([function(10) for function in functions])

    Invoke every saved function with 10 in list order.

Each factory call creates a distinct factor binding, so callbacks do not all use the same loop variable.

Predict before you run

Why is the last result 20 rather than every result being 20?

Capture each multiplierPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Use a negative factor.

Try: Replace range(3) with [-1, 0, 2].

The results become [-10, 0, 20] because multiplication uses each configured number.

Change the call argument.

Try: Use function(4) in the final comprehension.

The factors stay unchanged and the output becomes [0, 4, 8].

Before you move on

Let double = multiplier(2) and triple = multiplier(3). What are double(5) and triple(5)?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

They are 10 and 15. The two factory calls retain different factor bindings even though their inner code is identical.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Where this idea earns its place

A closure is useful when an operation needs a small configuration that should remain available after the configuring call returns. Examples include a multiplier, a validation rule or an event callback. Treat the captured state as a real dependency with a lifetime, not as invisible convenience.

Follow the mechanism step by step

Python resolves names through local, enclosing, global and built-in scopes according to its execution rules. A nested function can retain access to an enclosing binding. A loop normally reuses one binding for its target, so several later callbacks can all observe the final value rather than snapshots from their creation iterations.

Work through a concrete application

Trace a callback list built inside a loop, first recording the binding and then the time each callback is invoked. Repair it with a factory that creates a fresh enclosing binding for each iteration. An immutable default argument can capture a value too, but explain that this uses definition-time defaults rather than changing the general closure rule.

Failure cases and misleading shortcuts

Assigning to a name anywhere in a function can make that name local unless declared otherwise, which explains some UnboundLocalError cases. nonlocal deliberately rebinds an enclosing name; global changes module state. Neither declaration is a substitute for an explicit parameter when the dependency should vary between calls.

Cost, ownership and alternatives

Closures retain referenced objects, including large request contexts or caches. A callback registered globally can therefore keep data alive after its original request ends. A small closure may be simpler than a class, while multiple related transitions or inspectable state often justify an explicit object. Choose the representation around ownership and observability.

Verify the contract

Test callback results after the original loop or outer function has finished. Test two independently configured closures to detect accidental shared state, and inspect retained dependencies when measuring memory. Avoid an assertion that only calls the callback immediately during creation, since it can miss the late-binding failure entirely.

Transfer question: How would you make a stateful counter closure safe for concurrent callers?

First ask whether shared state is necessary. If it is, protect the complete read-modify-write transition with the appropriate synchronization primitive for the execution model, and define cancellation or reentrancy rules. nonlocal only controls binding scope; it provides no concurrency protection.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

When do ordinary closures read an enclosing binding?
TRANSFER THE IDEA

Rebuild: Capture each multiplier

Without copying the worked code, reproduce its observable contract: Each factory call creates a distinct factor binding, so callbacks do not all use the same loop variable. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Configure independent multipliers

Return one callable per factor in input order. Do not read a shared final loop value.

The contract

  • Input is a list of integers, including repeats, negatives or no factors.
  • Return a new list of independent callables; each accepts one integer and returns an int product.
  • Leave factors unchanged. Later edits to factors must not reconfigure returned callbacks.
Configure independent multipliersPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. Mixed factors
    source = [2, 3]
    result = make_multipliers(source)
    assert type(result) is list and len(result) == 2 and result is not source
    assert all(callable(f) for f in result) and [f(4) for f in result] == [8, 12]
    assert all(type(f(4)) is int for f in result) and source == [2, 3]
  2. Empty factory list
    source = []
    result = make_multipliers(source)
    assert type(result) is list and result == [] and result is not source and source == []
  3. Repeated factors
    source = [2, 2]
    result = make_multipliers(source)
    assert type(result) is list and len(result) == 2 and result[0] is not result[1]
    assert all(type(f(3)) is int and f(3) == 6 for f in result) and source == [2, 2]
  4. Negative and zero
    source = [-2, 0]
    result = make_multipliers(source)
    assert type(result) is list and len(result) == 2 and result is not source
    assert all(type(f(5)) is int for f in result) and [f(5) for f in result] == [-10, 0] and source == [-2, 0]
  5. Detached factors
    source = [4]
    result = make_multipliers(source)
    assert type(result) is list and len(result) == 1 and source == [4]
    source[0] = 9
    assert type(result[0](2)) is int and result[0](2) == 8
  6. Separate invocations
    source = [3]
    a = make_multipliers(source)
    b = make_multipliers(source)
    assert type(a) is list and type(b) is list and a is not b and len(a) == len(b) == 1
    assert a[0] is not b[0] and type(a[0](0)) is int and a[0](0) == b[0](0) == 0 and source == [3]
    Why not return lambda value: factor * value directly in the loop?

    Those callbacks would read one final loop binding. The factory gives each a distinct factor. Creating n callbacks costs O(n) time and space; each product uses ordinary integer arithmetic.

    GUIDED PRACTICE

    Own one counter per factory

    Build a counter that increments before returning its next value.

    The contract

    • start and step are integers; step may be zero or negative.
    • Return a callable with no arguments returning an int; the first result is start + step.
    • Do not use module state. Separate factory calls own independent counters; inputs are immutable integers.
    Own one counter per factoryPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. Counter case 1
      start, step = 0, 1
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [1,2]
      first_b = b()
      assert type(first_b) is int and first_b == [1,2][0]
      assert (start, step) == (0, 1)
    2. Counter case 2
      start, step = 5, 2
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [7,9]
      first_b = b()
      assert type(first_b) is int and first_b == [7,9][0]
      assert (start, step) == (5, 2)
    3. Counter case 3
      start, step = 0, -1
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [-1,-2]
      first_b = b()
      assert type(first_b) is int and first_b == [-1,-2][0]
      assert (start, step) == (0, -1)
    4. Counter case 4
      start, step = 4, 0
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [4,4]
      first_b = b()
      assert type(first_b) is int and first_b == [4,4][0]
      assert (start, step) == (4, 0)
    5. Counter case 5
      start, step = -3, 2
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [-1,1]
      first_b = b()
      assert type(first_b) is int and first_b == [-1,1][0]
      assert (start, step) == (-3, 2)
    6. Counter case 6
      start, step = 100, 10
      a = make_counter(start, step)
      b = make_counter(start, step)
      assert callable(a) and callable(b) and a is not b
      result = [a(), a()]
      assert all(type(value) is int for value in result) and result == [110,120]
      first_b = b()
      assert type(first_b) is int and first_b == [110,120][0]
      assert (start, step) == (100, 10)
      When is a class a clearer choice?

      When reset, inspection and other related transitions need names. This closure has one operation and constant extra state; each update has the cost of the integer addition.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: freeze threshold configuration

      Requirements changed: callbacks must filter later inputs using a snapshot of each configured threshold, not multiply a number.

      The contract

      • Input thresholds is a list of integers. Return a new list of functions in the same order.
      • Each function accepts a list of integers and returns a fresh list of values >= its threshold, preserving order and duplicates.
      • Never change thresholds or values. Later replacement of a threshold must not change existing callbacks.
      Transfer: freeze threshold configurationPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. Different thresholds
        limits = [2, 4]
        values = [4, 1, 2, 4]
        filters = make_filters(limits)
        assert type(filters) is list and len(filters) == 2 and filters is not limits
        results = [f(values) for f in filters]
        assert all(type(r) is list and r is not values for r in results) and results == [[4, 2, 4], [4, 4]]
        assert limits == [2, 4] and values == [4, 1, 2, 4]
      2. No configuration
        limits = []
        result = make_filters(limits)
        assert type(result) is list and result == [] and result is not limits and limits == []
      3. Empty values
        limits = [0]
        values = []
        filters = make_filters(limits)
        assert type(filters) is list and len(filters) == 1
        result = filters[0](values)
        assert type(result) is list and result == [] and result is not values and limits == [0] and values == []
      4. Boundary and repeats
        limits = [3]
        values = [3, 2, 3]
        filters = make_filters(limits)
        assert type(filters) is list and len(filters) == 1
        result = filters[0](values)
        assert type(result) is list and result == [3, 3] and result is not values and values == [3, 2, 3] and limits == [3]
      5. Detached threshold
        limits = [-1]
        filters = make_filters(limits)
        assert type(filters) is list and len(filters) == 1 and limits == [-1]
        limits[0] = 8
        values = [-2, -1, 0]
        result = filters[0](values)
        assert type(result) is list and result == [-1, 0] and result is not values and values == [-2, -1, 0]
      6. Fresh results
        limits = [1]
        values = [1, 2]
        filters = make_filters(limits)
        assert type(filters) is list and len(filters) == 1
        a = filters[0](values)
        b = filters[0](values)
        assert type(a) is list and type(b) is list and a == b == [1, 2] and a is not b and a is not values
        assert limits == [1] and values == [1, 2]
        What changed from a multiplier, and what stayed?

        The returned operation now builds an ordered filtered list, but each callback still owns its configuration. For n thresholds, creation is O(n); filtering m values costs O(m) time and up to O(m) result space.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        Retained state has a lifetime

        A closure can keep an object reachable for as long as the closure itself is reachable. Mutation affects that retained object even if the outer name has gone away.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Understand retained ownership when callbacks outlive a request or cache. A tiny function may keep a large object graph available.

        Words you will see

        Strong reference
        A connection that keeps an object reachable and available.
        Reachable
        Accessible through references from live program state.
        Snapshot
        A deliberate copy of selected state rather than a live view.

        The captured container stays live

        remember receives the same list that items names. read closes over that reference and returns a fresh list of its current elements each time. Appending outside the closure changes the source seen on the next call.

        The returned list is a shallow snapshot: changing its outer slots does not change items. Nested mutable elements would still be shared. Here the elements are integers, so a shallow copy is enough.

        Control lifetime through design

        Unregister callbacks and release no-longer-needed containers when their purpose ends. Do not infer exact collection timing from del: it removes a binding, not every possible owner.

        If a fixed historical result is required, copy the necessary data when creating the closure. For structured data decide the copy depth explicitly. Do not deep-copy files or network clients as if they were ordinary data.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. return list(values)

          Copy the currently retained list into a new outer list.

        2. items.append(2)

          Change the source before reading.

        3. result.append(9)

          Mutate only the returned copy.

        4. print(read())

          Read the source again; it has no 9.

        Closures can keep referenced objects alive, including large caches or request contexts. Keep captured state small, remove callbacks when no longer needed and inspect closure ownership when investigating memory growth.

        Predict before you run

        Will appending 9 to result change the next read?

        Live source, fresh resultPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Return the source directly.

        Try: Replace return list(values) with return values.

        Both prints include 9 because result is now the source itself.

        Capture a snapshot earlier.

        Try: Inside remember, set values = list(values) before defining read.

        The later source append is unseen; read returns [1] while result becomes [1, 9].

        Before you move on

        A closure returns list(source), where source contains another list. Is the nested list independent?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Only the outer list is new. Copy each required nested value, or use deepcopy for a supported data graph, if nested independence is promised.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Choose stateful abstractions deliberately

        nonlocal lets an inner function replace a binding in the nearest enclosing function scope. It does not create shared global state.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Use a closure for one small state transition, such as a private counter. Prefer a class when several operations must share and explain a larger state model.

        Words you will see

        Rebinding
        Changing which object a name refers to.
        nonlocal
        A declaration that assignments target an existing enclosing function binding.
        State transition
        A deliberate change from an old stored value to a new one.

        Read, add, replace

        count += 1 reads count, adds one, and rebinds count. Without nonlocal, Python treats count as local to advance; reading it before a local assignment raises UnboundLocalError.

        Two calls to counter create two independent count bindings. Repeated calls to one returned function update only its own binding. This is private state, not a guarantee of thread safety.

        Choose visible state when it grows

        A class can name operations such as reset and peek, and expose an explicit representation. Passing state in and returning updated state can be easier to test than hidden mutation.

        Do not declare nonlocal merely to mutate a captured list with append: append changes the object rather than rebinding the name. Use nonlocal only when replacement of the enclosing binding is the intended operation.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. count = 0

          Initialize state for one factory call.

        2. nonlocal count

          Direct assignments to the enclosing binding.

        3. count += 1

          Advance this counter by one.

        4. print(a(), a(), b())

          Evaluate left to right: a becomes 1 then 2, while b starts at 1.

        A closure works well for a small configured operation. A class can make several related state transitions easier to inspect. Do not use global or nonlocal mutation to hide dependencies that a parameter or explicit state object could explain.

        Predict before you run

        What happens if nonlocal count is removed?

        Keep counters separatePYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Advance by two.

        Try: Replace count += 1 with count += 2.

        The output becomes 2 4 2 because the counters remain independent.

        Share the same callback.

        Try: Replace b = counter() with b = a.

        The output becomes 1 2 3: a and b now name one stateful function.

        Before you move on

        If a counter starts at 10 and adds 2 per call, what do its first two calls return? What does a second fresh counter return?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        They return 12 then 14; the second counter returns 12. Each factory invocation owns its initial 10.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.