Name the equality you need
An archive editor needs to retrieve a record again after its tags change. A record snapshot can correctly treat the new tags as a different value; a source index must still recognize the same source. Making an object hashable is only part of that design. Its equality must also represent the intended key.
By the end, choose stable equality/hash fields, predict dataclass-generated behavior, expose the mutable value inside a frozen object and repair an index without merging equal content from different sources.
Lesson 4 separated object identity, values, aliases and copy boundaries. This lesson adds value records and hash-based keys. All data is constructed directly from supplied trusted strings/lists. The archive .json labels are source identifiers, not files opened here. No manifest/parser, schema validator or complete CLI is supplied.
Use final standard GIL-enabled CPython 3.15.1 and only its standard library. The exercised route is macOS ARM64/zsh; other operating systems and builds remain unverified for this walkthrough. No previous local file, environment, wheel cache, package installation, service or account is required.
Equality and hashing are a joint contract
is asks whether two expressions reach the same object. == can compare values
according to a type's equality method, named __eq__. A value record represents
selected data fields whose values determine equality. Independently constructed
records may then compare equal without being the same object.
A dictionary associates a key with a value. For hash-based lookup, hash(key)
obtains an integer through the key type's __hash__ method. A hash is a lookup
aid, not a unique identity, file checksum or serialized identifier. Hashable
objects require a stable hash over their lifetime, and equal keys must have
equal hashes. Unequal keys may have the same hash; that collision is permitted.
The dictionary still needs equality to distinguish keys.
Choose stable equality-relevant state as well, especially while an object is stored in a dictionary or set. Otherwise the same logical lookup can change meaning while the entry remains stored. An accepted call to hash is not proof that a proposed type preserves either requirement. Mutable objects with identity-based equality/hash can be valid keys, but that is a different policy from looking up a newly constructed key by source value.
Hashes involving strings can vary between Python processes. This lesson checks relationships and same-process stability, never a particular integer or an assumption that unequal keys must hash differently. It does not replace Python's hash machinery or promise a particular dictionary bucket layout.
What dataclass generates, and what it does not
A dataclass is an ordinary class processed by the standard-library dataclass
decorator. @dataclass above a class definition requests generated methods,
including an initializer, a readable representation and normally value equality.
The decorator is applied when the class is defined; instances are then created
by calling the resulting class. You do not need to implement decorators yet.
Declarations such as source: str identify a field with a type annotation.
In this lesson, list and tuple annotations simply name the intended container
kind. Dataclasses use annotations to discover fields; they do not validate
those field values or convert an incoming list into a tuple. Later lessons
teach more precise annotations and runtime boundary validation separately.
Generated equality compares included fields in declaration order and requires the identical concrete type on both sides. It does not automatically compare a dataclass instance equal to a dictionary or a different dataclass with the same displayed contents. The table assumes no custom equality/hash methods, no per-field exclusions and object as the base class:
| Configuration | Equality and hash consequence |
|---|---|
| Default dataclass | Generates field equality; sets __hash__ to None, so instances are unhashable |
| frozen=True | Generates field equality and a hash method; hash still fails if an included field is unhashable |
| eq=False | Leaves equality/hash inherited; with object as base here, separate instances use identity semantics |
| unsafe_hash=True | Forces a field-based hash method without freezing the fields; a mutable included field can still be unhashable, and changing hash/equality state can invalidate the design |
Frozen instances refuse ordinary field assignment/deletion. They do not recursively freeze referenced objects and are not a security boundary. A tuple also only fixes its own element references: a tuple containing a list is still unhashable. Our snapshots deliberately contain only strings and a tuple of strings, not arbitrary nested objects. Custom methods, inheritance or field exclusions require checking the resulting contract rather than applying this table blindly. The repair below needs none of those extra mechanisms.
Create a fresh value/key checkpoint
Run this group in zsh. The executable is the author-tested existing path;
substitute only your already approved executable if its path differs. &&
continues only after a successful preceding command:
AP_PYTHON='/opt/homebrew/bin/python3.15' &&
"$AP_PYTHON" -VV &&
AP_KEYS_ROOT="$(mktemp -d -t advanced-python-keys)" &&
printf '%s\n' 'advanced-python:lesson-5' > "$AP_KEYS_ROOT/.advanced-python-owner" &&
cd "$AP_KEYS_ROOT" &&
pwd
Keep the exact printed root and both variables in this terminal. Stop on failure. If the terminal closes, restore those exact saved values; do not search for a root using a broad wildcard. The marker detects ordinary context mistakes, not hostile filesystem changes. Both complete original programs and all their inputs follow; previous lesson files are not a hidden dependency.
Compare the actual value records
Predict which values can be hashed, which ordinary assignment fails and which nested append succeeds before running. Save this complete compare_records.py in the marked root:
from dataclasses import dataclass, FrozenInstanceError
from pathlib import Path
import sys
if (sys.implementation.name != "cpython"
or sys.version_info[:3] != (3, 15, 1)
or sys.version_info.releaselevel != "final"):
raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
raise SystemExit("STOP: standard GIL-enabled build required.")
if sys.flags.optimize:
raise SystemExit("STOP: run these self-checks without -O or -OO.")
owner = Path(".advanced-python-owner")
if owner.is_symlink() or not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-5":
raise SystemExit("STOP: use the marked lesson-5 root.")
@dataclass
class DraftRecord:
source: str
name: str
tags: list
@dataclass(frozen=True)
class FrozenListRecord:
source: str
name: str
tags: list
@dataclass(frozen=True)
class Snapshot:
source: str
name: str
tags: tuple
@dataclass(eq=False)
class IdentityKey:
source: str
@dataclass(unsafe_hash=True)
class MovingKey:
source: str
def expect_unhashable(value, label):
try:
hash(value)
except TypeError:
print(label + ": TypeError")
else:
raise AssertionError(label + " unexpectedly accepted a hash")
draft = DraftRecord("records/oak-a.json", "Oak ledger", ["local", "local"])
peer = DraftRecord("records/oak-a.json", "Oak ledger", ["local", "local"])
assert draft == peer and draft is not peer
print("draft equality:", draft == peer)
expect_unhashable(draft, "draft hash")
frozen = FrozenListRecord("records/oak-a.json", "Oak ledger", ["local", "local"])
assert draft != frozen, "generated equality requires identical concrete types"
try:
frozen.source = "records/oak-b.json"
except FrozenInstanceError:
print("frozen assignment: FrozenInstanceError")
else:
raise AssertionError("ordinary frozen field assignment was accepted")
snapshot = Snapshot(frozen.source, frozen.name, tuple(frozen.tags))
equal_snapshot = Snapshot("records/oak-a.json", "Oak ledger", ("local", "local"))
assert snapshot == equal_snapshot and snapshot is not equal_snapshot
assert hash(snapshot) == hash(equal_snapshot), "equal snapshot hashes differ"
frozen.tags.append("reviewed")
assert frozen.tags == ["local", "local", "reviewed"]
assert snapshot.tags == ("local", "local"), "snapshot retained mutable input"
changed_snapshot = Snapshot(frozen.source, frozen.name, tuple(frozen.tags))
assert changed_snapshot != snapshot
print("frozen tags:", frozen.tags)
expect_unhashable(frozen, "frozen-list hash")
print("snapshot lookup:", {snapshot: "found"}[equal_snapshot])
first = IdentityKey("records/oak-a.json")
second = IdentityKey("records/oak-a.json")
assert first != second and first is not second
identity_index = {first: "first", second: "second"}
assert len(identity_index) == 2
print("identity lookup: two entries for the same source")
moving = MovingKey("records/oak-a.json")
invalid_index = {moving: "stored before mutation"}
source_when_stored = moving.source
moving.source = "records/oak-b.json"
assert moving.source != source_when_stored
invalid_index.clear()
print("unsafe_hash: stored source changed; discard this index")
print("value self-checks: passed")
The first guards resupply the interpreter/build/current-GIL checks from earlier lessons. An ordinary guard rejects optimized execution because Python can omit assert statements under -O/-OO. The marker guard then checks this lesson's root. None of these context checks relies on an assert that optimization could remove.
DraftRecord uses default generated equality. Its two equal-valued instances are distinct objects, and its default hash is disabled. expect_unhashable calls hash inside a narrow try block, catches only the expected TypeError, and treats an unexpected success as a failed self-check. These are intentionally observed failures inside the example; the whole program can still succeed.
FrozenListRecord refuses rebinding source with FrozenInstanceError, an exception provided by dataclasses. The try/except/else verifies both paths: an unexpected accepted assignment raises AssertionError instead of printing a false pass. Its tags field still points to a mutable list. Appending reviewed mutates that list, so the freeze does not prevent the change; the generated hash then tries to hash the included list and raises TypeError. Setting frozen=True did not make every reachable value immutable or hashable.
Snapshot is frozen too, but we explicitly convert the trusted tag list with
tuple(frozen.tags). That makes a new immutable sequence of the supplied string
values, preserving order and duplicates. The nonempty literal
("local", "local") is a tuple, not a list. Subsequent input-list mutation does
not alter the snapshot's tuple. A separately constructed equal Snapshot has
the same hash in this process and retrieves the stored dictionary value. A new
snapshot made after the append is a different value because its tags differ.
IdentityKey suppresses generated equality. For these simple classes inheriting from object, its equal-looking source fields do not make two instances equal; the dictionary therefore keeps two entries. That is appropriate for identity keys but unsuitable for a source-value index's fresh-key lookup.
MovingKey forces generated hashing while leaving source assignable. Inserting it succeeds, then rebinding its equality/hash field violates our stable-source key policy. The example observes that field change and discards the tiny invalid index with clear. It deliberately makes no prediction about lookup after violating the contract, whether a particular hash integer changes or whether a particular lookup happens to miss. The correction is to prevent that state change, not to depend on the accidental result of a broken design.
Run, compare with your predictions and rerun unchanged:
"$AP_PYTHON" -I -B compare_records.py
Illustrative output (the author execution matched these values):
draft equality: True
draft hash: TypeError
frozen assignment: FrozenInstanceError
frozen tags: ['local', 'local', 'reviewed']
frozen-list hash: TypeError
snapshot lookup: found
identity lookup: two entries for the same source
unsafe_hash: stored source changed; discard this index
value self-checks: passed
The programs print only, reconstruct their tiny inputs in each process and create no report or worker. An unchanged rerun starts from the supplied state.
Repair an index around source identity
The source index's policy is now explicit: one key per source-path string; two different sources remain separate even when name/tags are equal. A new SourceKey with the same source must retrieve the same stored record. Editing name/tags must not change the key. These exercises do not permit source edits inside stored records; changing a source would need coordinated reindexing so the key and record still agree.
A plain source string would satisfy this policy too. The small SourceKey class makes the equality contract explicit for practice and provides a distinct key type. It does not validate a path, open that path or replace the archive schema. Tags/name belong in the editable dictionary value, outside this key.
Save this complete original repair_keys.py in the same root:
from dataclasses import dataclass
from pathlib import Path
import sys
if (sys.implementation.name != "cpython"
or sys.version_info[:3] != (3, 15, 1)
or sys.version_info.releaselevel != "final"):
raise SystemExit("STOP: final CPython 3.15.1 required.")
if sys.abi_info.free_threaded or not sys._is_gil_enabled():
raise SystemExit("STOP: standard GIL-enabled build required.")
if sys.flags.optimize:
raise SystemExit("STOP: run these self-checks without -O or -OO.")
owner = Path(".advanced-python-owner")
if owner.is_symlink() or not owner.is_file() or owner.read_text(encoding="utf-8").strip() != "advanced-python:lesson-5":
raise SystemExit("STOP: use the marked lesson-5 root.")
@dataclass(frozen=True)
class SourceKey:
source: str
def make_key(record):
return SourceKey(record["source"])
records = [
{"source": "records/oak-b.json", "name": "Oak ledger", "tags": ["local", "local"]},
{"source": "records/oak-a.json", "name": "Oak ledger", "tags": ["local", "local"]},
]
index = {}
for record in records:
index[make_key(record)] = record
assert len(index) == len(records) == 2, "distinct sources collapsed into one key"
probe = SourceKey("records/oak-a.json")
assert probe == make_key(records[1]), "same source keys compare unequal"
assert hash(probe) == hash(make_key(records[1])), "equal source hashes differ"
assert index[probe] is records[1], "fresh equal key did not retrieve its record"
before_hash = hash(probe)
records[1]["tags"].append("reviewed")
assert make_key(records[1]) == probe, "editing tags changed source identity"
assert hash(probe) == before_hash, "stored source hash changed"
expected_tags = [["local", "local"], ["local", "local", "reviewed"]]
assert [record["tags"] for record in records] == expected_tags, "tag values/order differ"
assert index[SourceKey("records/oak-a.json")]["tags"] == expected_tags[1]
assert records[0]["name"] == records[1]["name"] == "Oak ledger"
assert [key.source for key in index] == ["records/oak-b.json", "records/oak-a.json"]
print("sources:", [key.source for key in index])
print("lookup tags:", index[SourceKey("records/oak-a.json")]["tags"])
print("key self-checks: passed")
SourceKey has one immutable string field and generated frozen value equality/ hash. make_key extracts that field from a trusted constructed record; it does not coerce names into sources or validate arbitrary input. The loop builds a local dictionary keyed by those values. This is an in-memory source index, not the final sorted report: its displayed key order follows insertion order, oak-b then oak-a, while the reporting contract still sorts its final records.
The first assertion detects collapsing two sources. probe is freshly constructed; it must compare equal to the second record's key, share its hash and retrieve that exact stored record. The dictionary values intentionally reference the editable input records. Appending reviewed changes oak-a's tags, preserving both local values and the untouched first record. It does not change the source-only key. The complete tag prediction, fresh-key lookup and same-process hash check exercise that contract together. No deep copy is needed for index-key stability; a separate editor-ownership requirement could still need the lesson-4 copy boundary.
Run this complete group:
"$AP_PYTHON" -I -B repair_keys.py &&
printf '%s\n' 'current key run succeeded'
Illustrative output:
sources: ['records/oak-b.json', 'records/oak-a.json']
lookup tags: ['local', 'local', 'reviewed']
key self-checks: passed
current key run succeeded
Try three controlled faults one at a time, keeping the checks unchanged and restoring the complete supplied file between attempts:
-
Replace only the class's
@dataclass(frozen=True)with@dataclass. Predict the dictionary insertion failure. Default mutable value equality disables hashing, so this path raises TypeError rather than creating an index. -
Restore the original, then use
@dataclass(eq=False, frozen=True)for SourceKey. Hashing succeeds via object, but the fresh-key equality assertion fails. Freezing field assignment cannot repair the wrong equality policy. -
Restore the original, then replace only make_key with this deliberate faulty function excerpt, not a complete file:
def make_key(record): return SourceKey(record["name"])Both records have the same name. Dictionary assignment to an equal key updates the existing value; the count assertion detects the lost source. This is not a hash collision: the proposed keys are equal under their actual chosen field values. Restore make_key and require a successful current rerun.
On each intended failure, the shell's final success message must not print. Diagnose the first failing relationship or exception, not merely a nonzero exit. A syntax/name error after an incomplete edit is a different failure: restore both full files, rerun, then make one controlled edit. Assertions are enabled developer self-checks for supplied cases, not production input validation or proof of every input. Do not erase a failed check, accept the current output as the prediction or use optimization to hide it.
Check Your Understanding
Preserve the originals and attempt before opening the reasoning.
-
In the correct repair_keys.py, change the appended string from reviewed to audited. Write the complete expected_tags prediction before running; retain all count, equality, hash, source-order and fresh-key lookup checks. Which source changes and why can the new lookup key still find it? Verify, then restore the original edit/prediction and rerun.
-
A proposed index instead uses Snapshot(source, name, tuple(tags)) as its key. All supplied values are strings/tuples of strings. Is that key hashable and stable? After tags change, is a newly constructed snapshot equal to the old one? Explain whether it satisfies today's source-identity policy, and name a different policy under which the extra fields would be intentional.
-
A colleague passes a list as SourceKey's source because its annotation says str and they expect automatic conversion or rejection at construction. Predict the actual boundary. To observe it, insert this comparison excerpt immediately after make_key's complete definition in repair_keys.py, before records is built; leave the other code unchanged:
bad = SourceKey(["records/oak-a.json"]) hash(bad)Predict construction versus hash behavior, run the same group and explain what field validation is still missing. Remove the excerpt and rerun the complete original. Do not treat this deliberately wrong value as accepted archive input.
Answer and Reasoning
Hint 1: choose what a fresh key is allowed to forget
The source index asks whether two keys name the same source, not whether the source's current content is identical. Separate data used for lookup from data that the editor may change.
Hint 2: distinguish a generated method from its preconditions
A generated hash method still hashes the actual included values. A freeze blocks ordinary field replacement; it neither recursively freezes those values nor enforces their type annotations.
Compare your prediction
The first variation's complete data excerpt is:
expected_tags = [["local", "local"], ["local", "local", "audited"]]
records/oak-a.json at index one receives audited after both local values. The other source's tags stay unchanged. SourceKey still contains only that same source string, so a fresh equal key retrieves the same edited dictionary and the stored key's hash remains stable. Restore reviewed and its prediction.
The supplied Snapshot is hashable and stable for its actual string/tuple-of- string values. A later tag edit creates a different snapshot value, as the comparison program checks. Using all content as the key is therefore a different policy: a new-content lookup is not an equal-key lookup of the old snapshot. It could serve an in-memory cache of exact content snapshots, but would not satisfy the declared source-only index. Equal-looking values from different sources still need their distinct source fields. Hashability alone cannot choose the right business identity.
SourceKey accepts the wrong list at construction: dataclass annotations are not runtime validators. Its generated hash raises TypeError when it reaches that list. frozen=True and unsafe_hash=True cannot make a list field hashable. The correct examples assume trusted supplied strings; a later boundary must validate external inputs before constructing these keys. Remove the deliberate excerpt and restore the original successful run.
For all alternatives, compare relevant identities/values and the required hash relationships. Equal hashes alone do not prove equality; different objects can be equal. Neither frozen syntax nor a successful single hash call establishes a good key contract. No custom equality/hash implementation, bypass-resistant immutability, concurrency safety or persistent hash identifier is claimed here.
Inspect and clean up this checkpoint
Programs create no report files or helper bytecode under -B. Inspect the exact saved root and marker before cleanup:
cd "$AP_KEYS_ROOT" &&
test "$(cat .advanced-python-owner)" = 'advanced-python:lesson-5' &&
pwd &&
ls -la
Close the editor files. Inspect and remove an extra editor backup only by its explicit owned filename. After a partial setup, omit only source filenames confirmed absent. Remove these exact two scripts, marker and empty root:
cd "$AP_KEYS_ROOT" &&
test "$(cat .advanced-python-owner)" = 'advanced-python:lesson-5' &&
rm -- compare_records.py repair_keys.py .advanced-python-owner &&
cd .. &&
rmdir "$AP_KEYS_ROOT" &&
unset AP_KEYS_ROOT AP_PYTHON
rmdir refuses a nonempty directory. Stop and inspect a refusal; do not replace this sequence with recursive deletion. No earlier lesson root or environment is removed.
Sources and study views
The data model (S06) supplies equality/hash obligations and string-hash process limits. Dataclasses (S08) supplies the generation options, same-type equality, frozen limitations and annotation boundary. Built-in containers (S63) support tuples/dictionary keys, equality updates and insertion order. The assert statement (S61) explains optional developer checks. Resupplied context guards use the release baseline (S02), sys (S45), build/GIL distinction (S39) and pathlib (S16). All examples, policy choices and predictions are original course material.
Revision reconstructs the decisions; Quick Reference retrieves the taught operations. No diagram is needed: the options table and observed key/value operations directly show this lesson's distinctions.