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 33 / ADVANCED LANGUAGE FEATURES

Hashing, copying and object lifetime

Keep equality contracts consistent and choose ownership deliberately.

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 equality and hashing must agree
  • Apply copy the ownership boundary
  • Reason about frozen is not recursively immutable
01

Equality and hashing must agree

Hashing chooses where a dictionary or set looks for an object. Equal keys must have equal, stable hashes while stored.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use hashable values as keys for fast ordinary lookup. Equality alone is not enough: the lookup mechanism must be able to find equal candidates.

Words you will see

Hash
An integer used to organize lookup candidates; not a unique identifier.
Collision
Different values producing the same hash.
Hashable
Having a stable hash and equality behavior consistent with equal objects having equal hashes.

Equal values share a lookup promise

The two key tuples contain the same immutable field values, so they compare equal and hash equally. Storing both in a set leaves one entry. Different keys may collide, so equality still decides whether a candidate matches.

Tuple parentheses group the two fields into one key. A tuple is only hashable when every element is hashable. A tuple containing a list cannot become a safe key merely because its outer container is immutable.

Keep a key's meaning stable

Changing fields used by equality or hashing after insertion can make a stored key unreachable by the expected lookup. Prefer immutable key data, such as strings and tuples of immutable fields.

Defining __eq__ on a class without a suitable __hash__ normally makes instances unhashable. Do not patch this by hashing mutable fields. A list scan is a reasonable alternative for small collections or values without a stable hash contract.

The original example, step by step

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

  1. second = tuple(['room', 2])

    Construct the same field values through another expression.

  2. print(hash(first) == hash(second))

    Compare consistency, not a particular numeric hash.

  3. print(len({first, second}))

    The set recognizes equal keys as one entry.

If two keys compare equal, their hashes must match. A key's hash must remain stable while it is in a hash-based container. Mutable value-based objects usually should not be hashable. Defining equality without a consistent hash can break set/dict assumptions.

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. HashChoose candidate locations using a stable hash.
  2. CompareUse equality to distinguish collisions.
  3. Keep stableDo not mutate a key's hash-defining meaning after insertion.
Predict before you run

Can ('room', [2]) be hashed?

Equal keys, one entryPYTHON 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 a field.

Try: Make second = ('room', 3).

Equality becomes False and the set has two entries; do not require a particular unequal hash value.

Use a nested tuple.

Try: Replace 2 in both keys with (2, 3).

The keys remain hashable and equal because their nested elements are immutable and hashable.

Before you move on

Two unequal objects have the same hash. Must a dictionary treat them as one key?

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. That is a collision. Dictionary lookup also checks equality, so unequal candidates can remain separate keys.

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

Copy the ownership boundary

A shallow copy creates a new outer container but keeps references to its children. A deep copy follows supported data references to create an independent graph.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Choose copy depth from the ownership promise: a new dictionary alone does not isolate a nested score list.

Words you will see

Alias
Another reference to the same object.
Shallow copy
A new outer container whose nested objects are still shared.
Deep copy
A copy that recursively follows supported objects, remembering previously visited objects.

Follow the two reference layers

dict(original) copies the mapping entries into a new dictionary, but both scores entries refer to the same list. Appending through shallow['scores'] therefore changes original's list.

The dictionary identities differ, yet the nested identity is shared. Identity, tested with is, answers whether two references name the same object. Equality, tested with ==, answers whether their values compare equal.

Copy only what you own

For this narrow schema, {'scores': list(original['scores'])} is clearer than copying an arbitrary object graph. It gives the one nested list a new owner while reusing immutable integer elements.

deepcopy can preserve cycles and repeated references within its copied graph; it is not a promise to duplicate operating-system resources. Avoid copying locks, open files or remote clients. State whether other fields are kept or omitted when reconstructing explicitly.

The original example, step by step

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

  1. shallow = dict(original)

    Copy entries without copying the nested list.

  2. shallow['scores'].append(3)

    Mutate the list referenced by both mappings.

  3. print(shallow is original)

    The outer dictionaries are different objects.

  4. print(shallow['scores'] is original['scores'])

    Their scores values still name one list.

A shallow copy creates a new outer container with shared nested references. deepcopy recursively follows a graph and handles cycles, but can duplicate expensive or inappropriate resources. Prefer explicit reconstruction when you need only selected independent data.

Predict before you run

Which source value changes after the append?

See a shallow copy share a childPYTHON 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.

Reconstruct the nested list.

Try: Replace dict(original) with {'scores': list(original['scores'])}.

original stays [1, 2], and the nested identity comparison becomes False.

Replace rather than mutate.

Try: Use shallow['scores'] = [9] instead of append.

Only the shallow mapping's entry changes; original still points to [1, 2].

Before you move on

A copy of {'tags': ['a']} must allow appending to tags without touching the source. Is dict(source) sufficient?

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. Copy the tags list too, either by schema-aware reconstruction or an appropriate deep copy.

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

Make nested data independent

deepcopy can isolate nested data so an edit through the copy does not alter the original graph.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use it for supported data-only graphs when the required ownership boundary includes all their nested mutable containers.

Words you will see

Object graph
Objects and the references connecting them.
Independent nested state
Mutable children that are not shared across the copy boundary.
Copy memo
The deep-copy operation's record of objects already copied, used for repeated references and cycles.

Separate the score owners

deepcopy(original) creates a new dictionary and a new scores list. The local name copy refers to that result; it is not the copy module. Appending 3 through copy changes only the new nested list.

The original prints [1, 2]; the copy prints [1, 2, 3]. Immutable integer values do not need independent mutable storage. Deep copy follows data ownership, not a requirement that every object identity must differ.

An isolated graph can still contain shared parts internally

If two source entries point to one list, a single deepcopy operation normally makes their copied entries point to one new shared list. That preserves the source graph's internal relationships while separating it from the original.

Choose explicit reconstruction when you only need selected fields or must validate them. Copying an entire graph can be expensive in time and memory, roughly proportional to visited data for ordinary containers; custom copy methods can have other behavior.

The original example, step by step

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

  1. from copy import deepcopy

    Import the standard-library data-copy operation.

  2. copy = deepcopy(original)

    Copy the mapping and its supported nested graph.

  3. copy['scores'].append(3)

    Change the copied child.

  4. print(original['scores'])

    The original child has not changed.

The nested list is independent in this data-only graph; copying files, locks or remote clients is a different ownership problem.

Predict before you run

Why does original omit 3?

Make nested data independentPYTHON 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.

Try a shallow copy.

Try: Replace deepcopy(original) with dict(original).

Both score displays include 3 because the nested list becomes shared.

Add a second copied score.

Try: Append 4 through copy after appending 3.

Only the copied display grows to [1, 2, 3, 4]; the original remains unchanged.

Before you move on

source = {'a': shared, 'b': shared}. After one deepcopy(source), are the two copied values distinct from each other?

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

Normally no: both copied entries share one new child. That child is independent of shared, but internal aliasing is preserved.

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

Hashing, copying and weak references all depend on the distinction between an object's value, identity and ownership. They solve different problems: fast key lookup, independent data state and non-owning observation. Combining them without an explicit lifetime contract can produce missing keys, accidental sharing or unexplained cache behaviour.

Follow the mechanism step by step

A hash narrows the lookup location and equality resolves candidate matches. Equal objects must hash equally, and a stored key's hash must remain stable. Shallow copying creates new container references without recursively duplicating children. Weak references observe supported objects without being a strong owner that keeps them alive.

Work through a concrete application

Take a nested dict with a scores list and mutate a shallow copy to demonstrate the shared child. Reconstruct or deep-copy the supported data graph when independence is required. Then consider a cache: decide whether the cache owns values strongly, whether eviction is allowed and whether a miss must always be recoverable.

Failure cases and misleading shortcuts

A frozen outer model can still reference mutable contents. Deep-copying sockets, locks or clients is not a meaningful default strategy. A weak-value cache can lose entries when external owners disappear, so it cannot substitute for durable storage. Custom equality that ignores fields used by the hash violates the key contract.

Cost, ownership and alternatives

Copy cost depends on the traversed graph and stored values, not just the number of top-level keys. A bounded entry count also does not necessarily bound bytes. Strong caches improve reuse but retain data; weak caches reduce ownership but make availability dependent on other references. Measure against the actual workload.

Verify the contract

Test equal objects for equal hashes, key lookup before and after supported operations, nested mutation independence and cache-miss recovery. Do not assert exact object addresses or reference counts. If collection timing is relevant to diagnostics, treat it as implementation evidence rather than the correctness condition of the application.

Transfer question: Would you use weak references for a user's only copy of a report?

No. A weak reference deliberately does not own the report, so the object may disappear when no strong owner remains. Use an owned object or durable storage for required state, and reserve weak references for optional observation or recoverable caching.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

May a dict key safely change its value-based hash after insertion?
TRANSFER THE IDEA

Rebuild: Make nested data independent

Without copying the worked code, reproduce its observable contract: The nested list is independent in this data-only graph; copying files, locks or remote clients is a different ownership problem. 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

Copy a score report at its ownership boundary

Build an independent data-only report mapping names to lists of integers.

The contract

  • Input is dict[str, list[int]], possibly empty, with empty lists or repeated values.
  • Return a new dict with the same insertion order, keys and score values; each value is a fresh list.
  • Do not mutate input. Do not share a result list with the source or with another result entry, even if source values alias.
Copy a score report at its ownership boundaryPYTHON 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. Score ownership 1
    from copy import deepcopy
    source = {'a': [1, 2], 'b': [3]}
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
  2. Score ownership 2
    from copy import deepcopy
    source = {}
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
  3. Score ownership 3
    from copy import deepcopy
    source = {'a': []}
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
  4. Score ownership 4
    from copy import deepcopy
    source = {'a': [2, 2], 'b': []}
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
  5. Score ownership 5
    from copy import deepcopy
    source = {'a': [-1, 0]}
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
  6. Score ownership 6
    from copy import deepcopy
    source = {'a': [1], 'b': [1]}
    source['b'] = source['a']
    before = deepcopy(source)
    result = copy_scores(source)
    assert type(result) is dict and result == before and list(result) == list(source) and result is not source
    assert all(type(result[key]) is list and result[key] is not source[key] for key in source)
    assert len({id(value) for value in result.values()}) == len(result)
    for value in result.values():
        value.append(99)
    assert source == before
    Why reconstruct rather than deepcopy?

    The narrow schema needs one independent list per entry, including previously aliased entries. A single deepcopy preserves internal aliases instead. Copying k total score entries and n names takes O(n + k) time and output space.

    GUIDED PRACTICE

    Deduplicate immutable two-field keys

    Turn two-field rows into unique tuple keys, preserving first occurrence order.

    The contract

    • Input is a list of two-item lists [str, int]; empty and repeated rows are valid.
    • Return a fresh list of tuple[str, int] keys, retaining only the first occurrence of each equal pair.
    • Preserve the source rows. Later row replacements must not change result keys. Hash numbers must not be printed or persisted.
    Deduplicate immutable two-field keysPYTHON 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. Key case 1
      from copy import deepcopy
      rows = [['a', 1], ['b', 2], ['a', 1]]
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [('a', 1), ('b', 2)] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == [('a', 1), ('b', 2)]
    2. Key case 2
      from copy import deepcopy
      rows = []
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == []
    3. Key case 3
      from copy import deepcopy
      rows = [['x', 0]]
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [('x', 0)] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == [('x', 0)]
    4. Key case 4
      from copy import deepcopy
      rows = [['x', 1], ['x', 2]]
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [('x', 1), ('x', 2)] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == [('x', 1), ('x', 2)]
    5. Key case 5
      from copy import deepcopy
      rows = [['z', -1], ['a', 2], ['z', -1]]
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [('z', -1), ('a', 2)] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == [('z', -1), ('a', 2)]
    6. Key case 6
      from copy import deepcopy
      rows = [['a', 1], ['a', 1], ['a', 1]]
      before = deepcopy(rows)
      result = unique_keys(rows)
      assert type(result) is list and result == [('a', 1)] and result is not rows
      assert all(type(key) is tuple and len(key) == 2 and type(key[0]) is str and type(key[1]) is int for key in result)
      assert rows == before
      if rows:
          rows[0][0] = 'changed'
          assert result == [('a', 1)]
      Why not return list(set(...))?

      A set is useful for lookup but does not state first-occurrence order. For n fixed-size rows, expected lookup work is O(n) and storage is O(u) for u unique keys; collisions or expensive values can change those costs.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: observe without retaining ownership

      Requirements changed: build a read function for an optional weakly observed object, not a copied report.

      The contract

      • Accept a weakref.ref, or a zero-argument observer with the same protocol: return None or a live object with integer attribute value. Public probes model absence deterministically.
      • Return a fresh callable with no arguments. It returns the current int value if present, or the exact string 'missing' if absent.
      • Capture only the observer, never a strong target. Read the observer once per call; never modify the target or depend on collection timing.
      Transfer: observe without retaining ownershipPYTHON 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. Live observation 1
        import weakref
        class Box:
            pass
        owner = Box()
        owner.value = 0
        reference = weakref.ref(owner)
        read = make_weak_reader(reference)
        assert callable(read) and type(read()) is int and read() == 0 and owner.value == 0
        owner.value += 1
        assert type(read()) is int and read() == 1
        assert reference() is owner and owner.__dict__ == {'value': 1}
      2. Live observation 2
        import weakref
        class Box:
            pass
        owner = Box()
        owner.value = 7
        reference = weakref.ref(owner)
        read = make_weak_reader(reference)
        assert callable(read) and type(read()) is int and read() == 7 and owner.value == 7
        owner.value += 1
        assert type(read()) is int and read() == 8
        assert reference() is owner and owner.__dict__ == {'value': 8}
      3. Live observation 3
        import weakref
        class Box:
            pass
        owner = Box()
        owner.value = -2
        reference = weakref.ref(owner)
        read = make_weak_reader(reference)
        assert callable(read) and type(read()) is int and read() == -2 and owner.value == -2
        owner.value += 1
        assert type(read()) is int and read() == -1
        assert reference() is owner and owner.__dict__ == {'value': -1}
      4. Live observation 4
        import weakref
        class Box:
            pass
        owner = Box()
        owner.value = 100
        reference = weakref.ref(owner)
        read = make_weak_reader(reference)
        assert callable(read) and type(read()) is int and read() == 100 and owner.value == 100
        owner.value += 1
        assert type(read()) is int and read() == 101
        assert reference() is owner and owner.__dict__ == {'value': 101}
      5. Absent target without timing
        class Probe:
            def __init__(self):
                self.calls = 0
            def __call__(self):
                self.calls += 1
                return None
        probe = Probe()
        read = make_weak_reader(probe)
        assert callable(read) and probe.calls == 0
        result = read()
        assert type(result) is str and result == 'missing' and probe.calls == 1 and probe.__dict__ == {'calls': 1}
      6. One observation per call
        import weakref
        class Box:
            pass
        owner = Box()
        owner.value = 3
        reference = weakref.ref(owner)
        class Probe:
            def __init__(self):
                self.calls = 0
            def __call__(self):
                self.calls += 1
                return reference() if self.calls == 1 else None
        probe = Probe()
        read = make_weak_reader(probe)
        other = make_weak_reader(probe)
        assert callable(read) and callable(other) and read is not other and probe.calls == 0
        result = read()
        assert type(result) is int and result == 3 and probe.calls == 1 and reference() is owner and owner.value == 3
        missing = read()
        assert type(missing) is str and missing == 'missing' and probe.calls == 2 and owner.__dict__ == {'value': 3}
        Why keep the observed target in a local?

        It provides a stable temporary strong owner between the None check and attribute access. The closure must not keep that target between calls. Each read is constant auxiliary state, without a collection-timing claim.

        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

        Weak references are not ownership

        A weak reference observes a supported object without becoming the owner that keeps it alive.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Use weak references for optional observers or caches where losing an entry is acceptable. Required state needs a strong owner.

        Words you will see

        Weak reference
        A callable reference that yields the live target or None without retaining ownership.
        Strong owner
        A live reference that keeps the target reachable.
        Weak-value cache
        A mapping that does not own its values strongly, so missing values are normal.

        Observe while an explicit owner exists

        Box instances support weak references. owner is a strong reference; watch is not. While owner is held, watch() returns that same Box, so identity is predictable without waiting for collection.

        Reading watch() once into target creates a temporary strong owner. Check target is not None, then use target. Checking watch() and calling it again later can lose the target between the two reads in code with changing owners.

        Absence is part of the API

        Not every Python object supports weak references. Plain lists do not, and some slotted classes need a __weakref__ slot. A weak cache must rebuild on a miss rather than assume that prior insertion guarantees persistence.

        Do not test an exact moment after del when the target disappears. Collection strategy and other owners can differ between runtimes. This example deliberately holds owner and tests only the guaranteed live case.

        The original example, step by step

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

        1. owner = Box()

          Create a supported target with an explicit strong owner.

        2. watch = weakref.ref(owner)

          Add a non-owning observer.

        3. target = watch()

          Read the reference once and retain the result for use.

        4. print(target is owner)

          With owner live, the observed object is the same Box.

        weakref lets an observer refer to a supported object without keeping it alive. A weak-value cache may lose an entry when no strong owner remains; cache misses must be normal. Do not use weak references for data that must persist.

        Predict before you run

        With owner still strongly referenced, can watch() return an unrelated copied Box?

        Observe a strongly owned boxPYTHON 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.

        Read another field.

        Try: Set owner.value = 9 before target = watch().

        The value prints 9 because the observer sees the same live object.

        Confirm observer independence.

        Try: Add print(watch is owner).

        It prints False: the observer object is distinct even though watch() yields owner.

        Before you move on

        A cache value must survive until an invoice is sent. Is weakref alone sufficient ownership?

        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. Keep a strong reference for that required lifetime. Weak observers are suitable only when disappearance is an accepted outcome.

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

        Frozen is not recursively immutable

        A frozen dataclass prevents ordinary attribute reassignment, not mutation of objects referenced by its fields.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Choose immutable field values when records must act as stable value-based keys. Freezing only the outer object is not enough.

        Words you will see

        Dataclass
        A class whose common record methods can be generated from declared fields.
        Frozen
        Configured to reject ordinary field assignment after construction.
        Recursive immutability
        A property where referenced contents also cannot be mutated, not just the outer fields.

        A blocked assignment is only one boundary

        Record is frozen, so assigning record.tags = another_list is rejected. But record.tags.append('b') asks the existing list to mutate itself; it does not replace the field.

        The generated value-based hash would need to hash the tags list. That raises TypeError because a list is unhashable. frozen=True does not magically make every field hashable.

        Design stable value records

        Use a tuple of immutable strings for tags when order and repeats matter and changes should create a new record. A frozenset is different: it discards repeats and does not express sequence order.

        Test equality and hash consistency on the domain you actually accept. Do not use unsafe_hash as a shortcut around mutable field semantics. If identity rather than value matters, use an explicit identity-based design.

        The original example, step by step

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

        1. @dataclass(frozen=True)

          Generate a record that blocks ordinary field reassignment.

        2. record.tags.append('b')

          Mutate the referenced list, not the field binding.

        3. hash(record)

          Attempt a value hash that includes the unhashable list.

        4. print('unhashable field')

          Display the handled TypeError as a deterministic explanation.

        A frozen dataclass prevents ordinary attribute reassignment, not mutation of every referenced object. Choose immutable field values for stable hashable models, and test equality symmetry, transitivity and hash consistency.

        Predict before you run

        Does record.tags.append('b') raise a frozen-field assignment error?

        Frozen outside, mutable insidePYTHON 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 an immutable field.

        Try: Annotate tags as tuple[str, ...], construct Record(('a',)), and remove append.

        The hash attempt succeeds and the error message disappears; this avoids hashing a list.

        Create an independent record.

        Try: Build other = Record(list(record.tags)) and append 'c' to other.tags.

        Only other's list grows because it was explicitly copied; freezing alone did not supply that independence.

        Before you move on

        Would a frozen record holding a tuple of strings avoid this particular list problem?

        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

        Yes. Strings and their tuple are immutable and hashable, so the generated value hash can use them consistently. Other custom field types still need their own contracts.

        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.