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 48 / PERFORMANCE AND INTERNALS

CPython execution, references and GC

Understand internals without depending on unstable implementation details.

AdvancedTutorial 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 ready to reason about Python internals, resource boundaries and the listed prerequisites.

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 source is not executed as raw text each time
  • Apply separate semantics from implementation
  • Reason about version and build caveats
01

Source is not executed as raw text each time

Source must be valid before it can run. Compilation checks syntax and creates executable code; execution then performs the operations in that code.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A malformed program and a failing operation need different repairs. Separating the phases prevents changing runtime data in an attempt to fix invalid source.

Words you will see

Compilation
Turning valid source into a code object.
SyntaxError
An error raised when source does not follow Python grammar.
Runtime error
A failure while executing otherwise valid code.

Compile before running

compile receives source text, a diagnostic filename and the mode exec for statements. The valid text contains a division by zero, but compilation does not perform it. The program first prints compiled and only then encounters ZeroDivisionError inside exec.

The empty dictionary passed to exec supplies a separate namespace for this fixed trusted fixture. It is not a security sandbox. Never accept arbitrary learner or user text into a privileged host process merely because a namespace is provided.

Locate the failing phase

A missing colon can fail during compilation, before any earlier-looking statement in that same module executes. A missing dictionary key can fail only after valid code reaches its lookup. Tracebacks identify location and exception kind; both matter.

CPython compiles code objects and runs instructions, but other implementations can use different machinery while preserving language behavior. This fixture uses fixed text only. Browser execution still belongs in the approved isolated runner, not a new eval bridge.

The original example, step by step

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

  1. source = "value = 1 / 0"

    Provide fixed trusted source whose syntax is valid.

  2. code = compile(source, "<fixed-fixture>", "exec")

    Create code without performing the division.

  3. print("compiled")

    Show that compilation completed.

  4. except ZeroDivisionError:

    Handle the failure produced by executing the division.

CPython parses source, compiles code objects and executes bytecode. Imported modules can cache bytecode for startup, but this is not a guarantee of application speed. Syntax errors and runtime errors occur at different phases.

Conceptual phases, not a bytecode trace

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

  1. SourceText must satisfy the grammar.
  2. CompileCreate a code object or raise SyntaxError.
  3. ExecutePerform operations; data-dependent exceptions can now occur.
Predict before you run

Which line prints first?

Valid syntax can still fail when runPYTHON 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.

Make execution succeed.

Try: Change source to "value = 1 / 2".

Only compiled prints; there is no division failure.

Introduce invalid syntax.

Try: Change source to "if True".

Compilation raises SyntaxError before compiled can print.

Before you move on

A valid function contains a missing-key lookup but is never called. Must compiling its module raise KeyError?

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. Compilation checks the syntax; the lookup happens only when execution reaches it. Calling the function with the missing key can raise KeyError later.

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

Separate semantics from implementation

A code object describes executable instructions, while a function also carries the context needed to call those instructions. Introspection should answer a question, not become a portable opcode dependency.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Looking at selected metadata can connect a function definition with its call without asserting version-specific bytecode offsets or memory addresses.

Words you will see

Code object
The compiled representation of a block of Python code.
Function object
A callable combining code with globals, defaults and possibly captured context.
Bytecode
Interpreter instructions whose details depend on implementation and version.

Keep the public behavior primary

The sample defines echo with one positional parameter. co_name reports its code name and co_argcount reports one positional parameter. Calling echo with ready returns ready, independently of any instruction spelling.

dis can investigate a particular CPython build, but opcode names, adaptive specialization and offsets can change. A bytecode cache may reduce compilation at import startup; it does not eliminate module execution in every new process or fix a slow algorithm.

Context makes code callable

A code object alone does not supply every function's globals or captured values. Two functions can share a code pattern while using different defaults or closure contents. Validate their returned behavior rather than inferring it from a code name.

These attributes are for inspection on a supporting interpreter. Browser builds may differ. Do not make application correctness depend on integer interning, a printed address, an opcode list or a guessed reference count.

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 echo(value):

    Define a function with one positional parameter.

  2. metadata = echo.__code__

    Read its compiled code metadata.

  3. print(metadata.co_argcount)

    Display one, not a count of bytecode instructions.

  4. print(echo("ready"))

    Check observable function behavior separately from metadata.

The language defines observable behaviour; CPython's bytecode, reference counts and allocation strategies can change. Use dis to investigate a supported interpreter, not as a portable public API for application correctness.

Predict before you run

What is co_argcount here?

Inspect metadata without instruction addressesPYTHON 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.

Add a parameter.

Try: Change the definition to echo(value, extra=None).

co_argcount becomes two while the existing call still works.

Change behavior, not call shape.

Try: Return value.upper() instead.

The result becomes READY; parameter count remains one.

Before you move on

Two functions have the same number of parameters. Does that prove they compute the same result?

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. Parameter count describes one part of a call shape. Instructions, globals, defaults and captured values can produce different behavior.

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

Inspect a code object's public identity

A small metadata observation can be useful without revealing unstable execution internals. Keep the result of a function call distinct from the description of its compiled code.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The original add program offers an inspection starting point that remains readable without teaching a particular bytecode listing as a language guarantee.

Words you will see

co_name
The name recorded for a compiled code block.
co_argcount
The number of positional parameters, including positional-only parameters.
Implementation detail
A mechanism a particular runtime may change without changing the language's intended behavior.

Read the original add program

def add(a, b) creates a function whose body returns a + b. The two metadata prints report add and 2. The final call supplies integers 2 and 5, so addition returns 7. The metadata lines describe the function rather than running its body.

A parameter is a named input in the definition; an argument is a supplied value in a call. co_argcount does not count how many total calls occurred, nor every possible keyword-only parameter. Inspect the right attribute for the question.

Limit the claim

The sample does not print object identities, addresses or bytecode. That avoids teaching one build's layout as a universal fact. A module's cached bytecode and a live function object are also different things: caching compilation is not caching every result.

Use behavioral tests for correctness. If an investigation truly needs disassembly, state the runtime version and build and treat the listing as optional depth. A browser build need not reproduce a host's instruction representation.

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 add(a, b):

    Define two positional parameters.

  2. return a + b

    Compute addition only when called.

  3. print(add.__code__.co_name)

    Display the code block's name, add.

  4. print(add(2, 5))

    Call the function and display seven.

The example examines stable code-object metadata without asserting a version-specific bytecode listing or memory address.

Predict before you run

What does add(2, 5) display?

Inspect a code object's public identityPYTHON 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.

Change the arguments.

Try: Call add(3, 8) instead.

The result becomes 11 while the name and parameter count stay unchanged.

Use compatible strings.

Try: Call add("a", "b") instead.

The result is ab because + joins strings; metadata still does not determine the argument types.

Before you move on

If add is called twice, does co_argcount become four?

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. It remains two because it describes declared positional parameters, not a history of calls.

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

Trace execution through distinct phases

CPython first parses source and compiles code objects, then executes instructions associated with those objects. A malformed function definition can prevent a module from compiling at all, while an invalid operation inside a valid function may fail only when the function is called. This distinction helps locate a failure: changing runtime input cannot fix a syntax error that prevents the program from reaching its input boundary.

The add example reports the function code object's name, its positional argument count, and the result of adding 2 and 5. The outputs add, 2, and 7 illustrate metadata and observable behavior without depending on an instruction listing. A function object also carries contextual information such as its globals and defaults; a code object alone is not the complete execution environment of every possible function.

Investigate instructions without making them a contract

dis can help explain how a supported CPython version executes an expression, but instruction names, specialization, and layout can change across releases. Begin with a behavioral question, inspect the relevant function, and compare your inference with a test of the behavior. Do not build application validation around a particular opcode sequence. A different interpreter can implement the same Python semantics through very different internal mechanisms.

Cached bytecode for imported modules can avoid some repeated compilation work, but it does not remove module execution in a fresh process or make an inefficient algorithm efficient. A module cache within a process and a bytecode cache on disk solve different problems. Diagnose startup by distinguishing compilation, imports, and top-level side effects before claiming that deleting cache files or precompiling modules will address a measured slowdown.

Follow references before reasoning about reclamation

Names and containers hold references to objects. Rebinding a local name removes one reference relationship but does not destroy an object that another owner still retains. In conventional CPython, reference counting handles many unreachable objects promptly, while cyclic collection can find certain unreachable container cycles. Neither mechanism can reclaim a cache entry that remains strongly reachable merely because the application considers its request finished.

Draw a small ownership graph when memory seems unexplained: function to default list, cache to result, callback to closure, closure to request. Removing one edge may be enough, or another owner may remain. Avoid interpreting incidental reference-count readings as stable business rules because inspection itself can introduce references. Collection timing and finalization behavior vary; resource release must be an explicit program responsibility rather than an experiment with object destruction.

Make resources and concurrency correct independently

Use context managers or explicit finally cleanup for files, connections, and locks. An open file retained inside a suspended generator can remain live after the caller stops consuming it, even if each yielded item is small. Specify who closes the generator or the resource and verify early-exit paths. A correct cleanup design does not depend on a particular interpreter collecting an abandoned object immediately after a function returns.

Record the interpreter version and build before evaluating concurrency behavior. Conventional GIL-enabled CPython does not make arbitrary multi-step shared-state operations transactionally safe, and optional free-threaded builds change performance assumptions further. Threads can help suitable blocking I/O, while CPU-heavy Python workloads may need processes or native implementations. Process isolation adds serialization, startup, and ownership costs; internal interpreter knowledge informs that choice but cannot replace workload measurement and synchronization.

Transfer question: A developer says a file will close safely because CPython destroys local variables immediately. How would you review that argument?

Reject the timing dependency and identify the actual file owner. The object might be retained by a generator, traceback, callback, or another container, and a different runtime need not finalize it at the same moment. Require a context manager or explicit finally path around the intended lifetime. Test normal completion, an exception during reading, and early termination by the consumer. If a generator owns the file across yields, provide a documented closing protocol or move ownership to an outer context. The desired guarantee is deterministic program control over cleanup, not a guessed reference count.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

Should program correctness depend on an exact CPython bytecode instruction sequence?
TRANSFER THE IDEA

Rebuild: Inspect a code object's public identity

Without copying the worked code, reproduce its observable contract: The example examines stable code-object metadata without asserting a version-specific bytecode listing or memory address. 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

Guided: distinguish syntax from execution

Classify fixed source strings by compilation alone. Never execute the supplied source.

The contract

  • Input is a bounded string of Python statements; NUL-containing and oversized strings are outside this exercise's domain.
  • Return exactly 'ready' if compile succeeds or 'syntax' if it raises SyntaxError.
  • Do not exec or eval the source. Its runtime failures or side effects must not occur; the string is immutable.
Guided: distinguish syntax from executionPYTHON 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. valid assignment
    import copy
    
    source = "value = 3"
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "ready"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  2. empty source
    import copy
    
    source = ""
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "ready"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  3. repeated statements
    import copy
    
    source = "x = 1\nx = 1"
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "ready"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  4. syntax failure
    import copy
    
    source = "if True"
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "syntax"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  5. runtime failure is still compiled
    import copy
    
    source = "raise RuntimeError()"
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "ready"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  6. side effects must not execute
    import copy
    
    source = "print(99)\n1 / 0"
    before = copy.deepcopy(source)
    result = compile_status(source)
    assert type(result) is str, "Wrong result type"
    expected = "ready"
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
    Does ready mean safe or correct?

    No. It means this source compiled. Compilation takes work and storage proportional to source structure; it proves neither runtime success nor safety. Untrusted execution still belongs in the approved sandbox.

    GUIDED PRACTICE

    Guided: copy one mutable level

    Produce independently editable row lists while reusing immutable integer leaves.

    The contract

    • Input is a list of integer lists; empty rows and repeated references are allowed.
    • Return a new outer list and a new list for every row occurrence, preserving values and order.
    • Do not modify the source. Output rows must not alias source rows or each other, even when two source rows are the same object.
    Guided: copy one mutable levelPYTHON 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. two rows
      import copy
      
      source = [[1, 2], [3]]
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = [[1, 2], [3]]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      assert all(a is not b and type(a) is list for a, b in zip(result, source))
    2. no rows
      import copy
      
      source = []
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = []
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      
    3. equal rows stay independent
      import copy
      
      source = [[2], [2]]
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = [[2], [2]]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      assert result[0] is not result[1]
      result[0].append(9)
      assert result[1] == [2] and source == before
    4. empty row ownership
      import copy
      
      source = [[]]
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = [[]]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      assert result[0] is not source[0]
    5. source alias is split
      import copy
      shared = [4]
      source = [shared, shared]
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = [[4], [4]]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      assert result[0] is not result[1] and result[0] is not shared and result[1] is not shared
    6. output mutation stays local
      import copy
      
      source = [[-1, 0]]
      before = copy.deepcopy(source)
      result = copy_rows(source)
      assert type(result) is list, "Wrong result type"
      expected = [[-1, 0]]
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      assert result is not source, "Return a fresh container"
      result[0][0] = 8
      assert source == before
      Would this suffice for lists containing dictionaries?

      No. It copies only outer and row lists. For m integer leaves and b rows it takes O(m+b) work and storage. A deeper mutable-leaf contract needs deeper copying or a different representation.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: callbacks retain each integer

      Instead of returning copied values now, return one no-argument reader per input value for later use.

      The contract

      • Input is a finite list of integers, including repeats.
      • Return a fresh list of callable readers in input order; each no-argument call returns its original integer, repeatedly.
      • Do not mutate or retain the input list. Replacing an input entry after construction must not affect any reader.
      Transfer: callbacks retain each integerPYTHON 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. independent captures
        import copy
        
        source = [1, 2, 3]
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = [1, 2, 3]
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        assert all(callable(read) and type(read()) is int for read in result)
      2. empty callback list
        import copy
        
        source = []
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = []
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      3. repeated values
        import copy
        
        source = [4, 4]
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = [4, 4]
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        assert [read() for read in result] == [4, 4]
      4. zero and negatives
        import copy
        
        source = [0, -3]
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = [0, -3]
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        
      5. single reusable reader
        import copy
        
        source = [9]
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = [9]
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        assert result[0]() == result[0]() == 9
      6. later caller replacement
        import copy
        
        source = [7, 8]
        before = copy.deepcopy(source)
        result = value_readers(source)
        assert type(result) is list, "Wrong result type"
        expected = [7, 8]
        observed = [read() for read in result]
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert result is not source, "Return a fresh container"
        source[:] = [99]
        assert [read() for read in result] == [7, 8]
        Is capturing a mutable list as a default equivalent to freezing its content?

        No. A default retains an object reference, not a deep copy. These immutable integers are safe under this contract. Creating n callbacks takes O(n) work and storage.

        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

        References and cycles

        References form an ownership graph. Removing one name does not reclaim an object retained by another container, and a cycle is not automatically a leak.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Reference counting explains many conventional CPython lifetimes, while cyclic collection can handle some unreachable cycles. Neither is a safe schedule for closing external resources.

        Words you will see

        Reference
        A connection from a name or object to another object.
        Cycle
        A path of references that leads back to an earlier object.
        Finalization
        Cleanup associated with an object's end of lifetime, whose timing should not define resource correctness.

        Reachability comes before reclamation

        The list refers to itself. holder then retains that list. Deleting node removes one name but holder[0] still reaches the list, whose first entry points to itself. The is expression observes this relationship without printing a recursive representation.

        Conventional CPython uses reference counts and a collector for many unreachable container cycles. If holder is still reachable, the cycle is not unreachable garbage. Free-threaded builds and other interpreters can differ in lifetime details; avoid promising immediate destruction.

        Own resources explicitly

        Files, locks and connections need context managers or finally cleanup at the intended boundary. A traceback, generator or callback may retain an object longer than the author expects. An application should not depend on __del__ happening when a local name disappears.

        This example proves a reference relationship, not a collection time or allocated byte count. Identity with is asks whether two references reach the same object. Equality with == asks a different question and is a poor tool for diagnosing recursive ownership.

        The original example, step by step

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

        1. node.append(node)

          Make a list whose entry refers to itself.

        2. holder = [node]

          Retain the cyclic list through an outer owner.

        3. del node

          Remove the local name, leaving holder's reference.

        4. holder.clear()

          Remove the outer owner's entry without asserting when collection occurs.

        CPython combines reference counting with cyclic collection for many container cycles. Exact collection timing varies across implementations and runtime configurations. Use context managers for files and locks, not __del__ timing or a guessed reference count.

        Predict before you run

        Why does the identity comparison print True?

        An owner keeps a cycle reachablePYTHON 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.

        Remove the self edge.

        Try: Replace node.append(node) with node.append([]).

        The identity comparison becomes False.

        Keep a second outer owner.

        Try: Assign backup = holder[:] before holder.clear(), then print(len(backup)).

        backup still contains one reference; clearing holder did not clear the copied outer list.

        Before you move on

        A callback still retains a cyclic request object. Would forcing collection make the reachable request disappear?

        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. Identify and remove the callback's ownership when appropriate. Reachable state is not collectible merely because the request is logically finished.

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

        Version and build caveats

        A closure can read a captured variable later, while a default argument is evaluated when the function is created. The two mechanisms can produce different results in a loop.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Callbacks created in a loop often need one independent value each. Explaining when the value is chosen prevents every callback from accidentally reading the final loop value.

        Words you will see

        Closure
        A function retaining access to variables from an enclosing function scope.
        Late binding
        Reading a variable's current value when the function runs.
        Default argument
        A value computed at function definition time and used when no corresponding argument is supplied.

        Separate variable capture from value capture

        late contains three functions that read the same enclosing variable number. After the loop that variable is 3, so all three calls return 3. frozen uses a default parameter to store the current integer for each new function, producing 1, 2 and 3.

        This is a language-level lookup distinction, not evidence about opcode addresses. The factory function supplies a genuine enclosing local scope. At module level a similar lambda may read a global rather than a closure cell.

        Defaults are not deep copies

        Capturing an immutable integer as a default is straightforward. Capturing a list retains the same mutable object, so later mutations remain visible. Use a deliberate copy only when the contract requires independent mutable state, and define the copy depth.

        For complex callback construction, a named factory can be clearer than a dense lambda. Conventional CPython's GIL does not turn multi-step callback state changes into transactions. Thread safety requires a separate synchronization and ownership design.

        Runtime build is part of the evidence

        The GIL, or global interpreter lock, coordinates execution in conventional CPython builds; it is not an application transaction lock. Optional free-threaded builds change concurrency and performance assumptions. Record the version and build before comparing threaded callbacks, and check native extension compatibility rather than assuming every installed wheel supports that build.

        Threads can suit blocking input and output, while CPU-heavy Python work on a conventional GIL-enabled build may benefit from processes or suitable native code. Processes add startup and serialization costs and change ownership boundaries. Browser Python is not a host multiprocessing environment. None of these execution choices changes the late-binding rule demonstrated here; choose synchronization and workload measurements separately.

        The original example, step by step

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

        1. late.append(lambda: number)

          Keep access to the shared enclosing variable.

        2. frozen.append(lambda value=number: value)

          Store this iteration's integer as a default.

        3. return late, frozen

          Return two newly built callback lists.

        4. print([read() for read in frozen])

          Call each frozen callback and observe its independent integer.

        Adaptive interpreter optimisations, optional free-threaded builds and native extensions affect performance/concurrency assumptions. Record the runtime build when profiling. Do not make a correctness argument depend on incidental integer caching or object interning.

        Predict before you run

        What does the late list produce?

        Choose when callback inputs are capturedPYTHON 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.

        Shorten the input.

        Try: Use [1, 2] in the loop.

        Late callbacks both return 2; frozen callbacks return 1 and 2.

        Use a named factory.

        Try: Replace the frozen lambda with a helper returning a function whose own enclosing argument is number.

        Each helper invocation owns a separate binding, preserving the per-iteration values.

        Before you move on

        If each callback captures a list using a default and that list later changes, is the old content guaranteed to remain frozen?

        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. The default retains a reference to the list. Copy to the required depth if independent content, rather than a retained object, is the contract.

        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.