Python's data model and special methods
Make objects work naturally with built-in protocols.
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.
- Explain implement a coherent protocol
- Apply representations serve different readers
- Reason about avoid surprising costs
Implement a coherent protocol
A protocol is a set of operations an object supports. Special methods connect your objects to Python syntax such as len, iteration and membership.
Understand first
Callers already know len, for and in. Implement the matching special methods when those operations make sense for your model, rather than inventing unrelated names for familiar behavior.
Words you will see
- Protocol
- A documented group of operations supported by an object.
- Dunder
- Informal name for a special method with double underscores at both ends.
- Iterable
- An object that can provide an iterator over its values.
Keep the operations consistent
Bag copies the input's entries into a tuple. __len__ reports the number of entries, not the number of distinct values. __iter__ returns a fresh tuple iterator. __contains__ searches those same entries, so membership agrees with iteration.
Three entries include tea twice, so length is three and the list display retains both teas. Membership returns a bool and does not remove a matching entry. An empty bag naturally has length zero, iterates no entries and contains nothing.
Implement only what the model can promise
This bag has no item-assignment method and no ordering comparisons. It does not need to impersonate every built-in collection. A class exposing len must return a nonnegative integer; negative values raise ValueError and non-integers raise TypeError when len is called.
Constructing from n entries takes linear work and space. Length of the stored tuple is constant time; membership may inspect up to n entries. The outer tuple owns its entry sequence, but nested mutable entry objects are not recursively copied. Recap: syntax integration is a behavioral contract, not just a set of method names.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
self._items = tuple(items)Snapshot the entry sequence without removing duplicates.
return len(self._items)Use the same stored sequence for length.
return iter(self._items)Create an independent cursor each time.
print("tea" in bag)Route membership through __contains__.
__len__, __iter__, __contains__ and __getitem__ let objects participate in familiar operations. Implement only behaviours your abstraction can support meaningfully. Pretending to be every container usually creates inconsistent expectations.
Conceptual protocol dispatch and ownership, not a live runtime trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- SnapshotThe caller's list supplies entries to a new tuple; future list appends cannot extend the bag.
- Dispatchlen(bag), iter(bag), and item in bag request the corresponding class-defined special methods.
- AgreeAll methods consult the same tuple, so length, traversal and membership describe one collection.
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 all entries.
Try: Use Bag([]).
Length is 0, the list is [], and both membership checks are False.
Check iterator independence.
Try: Append print(list(bag), list(bag)).
Both traversals return the full sequence because each starts a new cursor.
Before you move on
What should len(Bag([])) and 'tea' in Bag([]) produce?
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
Zero and False. Empty input is still a valid bag and all three supported operations agree about having no entries.
Representations serve different readers
__repr__ is a useful diagnostic description; __str__ is user-facing text. Neither is permission to reveal secrets.
Understand first
Good diagnostics help a reader identify what kind of object they are inspecting. A separate friendly form can fit user-facing text. Both are likely to appear in logs and error reports, so select fields deliberately.
Words you will see
- repr
- The diagnostic string requested by repr(obj), often also used inside containers.
- str
- The user-facing string requested by str(obj) and usually print(obj).
- !r
- An f-string conversion that uses repr for the embedded value.
Make output informative without overpromising
Ticket.__repr__ includes the class name and a quoted code using !r. It deliberately omits _token. __str__ returns the friendlier Ticket A7. The list display uses repr(ticket), not str(ticket), to describe its entry.
A repr should be unambiguous and useful, but need not always be executable code that reconstructs the object. This repr cannot restore the omitted token and should not try. Both methods must return strings.
Data selection is the protection
A leading underscore on _token does not stop accidental printing if you include it in repr. Avoid dumping self.__dict__ into representations. Choose safe identifiers, and separately define which identifiers are appropriate to log.
If __str__ is absent, object behavior falls back toward repr. If __repr__ is absent, the default often includes a type and identity-like address, which is unsuitable for deterministic expected output. Do not assert exact object addresses. Recap: customize representations for readers, not for automatic secrecy or serialization.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return f"Ticket(code={self.code!r})"Quote the code and omit the private token.
return "Ticket " + self.codeProvide a simple user-facing string.
print(repr(ticket))Request the diagnostic form explicitly.
print([ticket])A container also uses the diagnostic form for its element.
__repr__ is primarily a diagnostic representation; __str__ is user-facing text. Neither should expose secrets. Implementing __iter__ allows for loops and other consumers to use the same iteration contract.
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.
Observe the fallback.
Try: Remove __str__ and its return line.
str(ticket) now uses the diagnostic representation.
Observe escaped text.
Try: Change the code argument to "A\n7".
repr shows an escaped newline; the user-facing string contains a real line break.
Before you move on
If code contains a newline, why is !r useful in the diagnostic form?
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
repr of the string shows an escaped newline inside quotes, making the stored value easier to distinguish from an actual line break in output. It does not sanitize every possible logging risk.
A small iterable range wrapper
A repeatable iterable can provide a fresh cursor for each traversal. A stable outer snapshot also separates its entry sequence from later edits to the source list.
Understand first
The original Scores example makes sum and len useful without exposing the caller's mutable list. A second traversal should still see the same stored values.
Words you will see
- Iterator
- A cursor that supplies successive values and eventually raises StopIteration.
- Snapshot
- A stored sequence reflecting the source at construction time.
- Shallow snapshot
- A new outer container that still refers to the same entry objects.
Storage and cursor are different jobs
Scores stores tuple(values), not iter(values). __iter__ returns iter(self._values), creating a new cursor whenever Python asks for a traversal. sum can consume one cursor without exhausting the Scores object.
For [3, 5], length is two and sum is eight. repr shows Scores((3, 5)) because !r represents the stored tuple. The object has no __next__; it is the iterable that produces iterators, not one shared iterator itself.
State exactly what was copied
Appending to the original input list cannot add entries to _values. But if an entry were a nested list, changing that nested list would still be visible through the tuple. The numeric example avoids that extra ownership question.
Construction takes linear work and storage for n source entries. Each iterator has its own cursor with constant extra state; traversing n numbers is linear. Creating a tuple from a never-ending iterator would not finish, so this constructor requires finite input. Recap: repeatability comes from fresh cursors over retained values.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
self._values = tuple(values)Store the finite sequence once.
return iter(self._values)Produce a new cursor rather than retaining a consumed one.
print(len(scores), sum(scores))Ask separate protocols for size and aggregation.
return f'Scores({self._values!r})'Represent the snapshot with the tuple's diagnostic form.
A stable internal tuple supports repeated iteration without exposing the original mutable list. Each call to iter creates a fresh cursor over those stored values.
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.
Traverse twice.
Try: Append print(sum(scores), sum(scores)).
Both values are 8.
Prove outer input independence.
Try: Construct from values = [3, 5], then values.append(9) before printing.
The stored length, sum and repr stay unchanged.
Before you move on
After sum(scores), what does list(scores) produce for the original example?
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
[3, 5]. list requests a new cursor from the retained tuple, so the earlier sum did not consume the iterable's stored data.
Where this idea earns its place
Python's built-in operations are interfaces to protocols. Making a custom object iterable or length-aware allows ordinary tools to work with it without requiring callers to know its representation. Implement a coherent small contract rather than adding special methods simply to make the object resemble every built-in container.
Follow the mechanism step by step
len, iteration and membership dispatch through defined operations on the type. The Scores example stores a tuple, returns its length and creates a fresh iterator when requested. sum can then consume that iterator without accessing _values directly. A repr serves diagnostics and should describe useful state without leaking secrets.
Work through a concrete application
Begin with the operations callers actually require. If repeated traversal is promised, return a new iterator each time rather than returning one exhausted cursor stored on the object. If indexing is added, decide which indexes and slices are supported and which exceptions represent invalid access.
Failure cases and misleading shortcuts
Special-method lookup is not always ordinary instance attribute lookup, so assigning a method-like value to one instance can fail to affect len or operators. Returning NotImplemented for an unsupported binary operand is different from raising NotImplementedError. Inconsistent equality and hashing can also break otherwise familiar container operations.
Cost, ownership and alternatives
Protocols should communicate costs. A length operation that scans a remote dataset or an attribute read that performs network I/O may surprise callers. A stable internal snapshot trades memory for predictable iteration, while a live view may expose concurrent mutation. State those trade-offs instead of assuming protocol syntax guarantees cheap local behaviour.
Verify the contract
Write tests using the public built-in operations: len, iteration, membership and representation where promised. Include repeated traversal, empty data and unsupported operands. Check that callers cannot mutate an allegedly immutable snapshot through a retained reference and that diagnostic output excludes private fields.
Transfer question: Should you implement __getitem__ merely to make a stream look like a list?
Only if random access has a sensible supported contract and cost. A one-way stream may be better exposed as an iterable. Materialising or replaying the source secretly to satisfy an index can create surprising latency, memory use or repeated side effects.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: A small iterable range wrapper
Without copying the worked code, reproduce its observable contract: A stable internal tuple supports repeated iteration without exposing the original mutable list. Each call to iter creates a fresh cursor over those stored values. Then change one boundary input and explain the result.
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 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.
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.
Build a repeatable score collection
Return a Scores object that integrates with len, iteration and repr while owning a snapshot of the input entries.
The contract
- values is a finite iterable of integers, including repeats, negatives and empty input.
- Return an object whose type is named Scores and implements __len__, __iter__ and __repr__. repr must be Scores(<tuple repr>).
- Store a tuple snapshot. Each iteration starts a fresh cursor; source-list changes must not affect values, length, sum or repr.
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.
- Protocols and representation
s = make_scores([3, 5]) assert type(s).__name__ == "Scores" and len(s) == 2 and type(len(s)) is int and list(s) == [3, 5] and sum(s) == 8 and type(repr(s)) is str and repr(s) == "Scores((3, 5))"
- Empty scores
s = make_scores([]) assert type(s).__name__ == "Scores" and len(s) == 0 and list(s) == [] and sum(s) == 0 and repr(s) == "Scores(())"
- Repeats and singleton syntax
s = make_scores([2, 2, -1]) t = make_scores([7]) assert len(s) == 3 and list(s) == [2, 2, -1] and sum(s) == 3 and repr(s) == "Scores((2, 2, -1))" and type(t).__name__ == "Scores" and repr(t) == "Scores((7,))"
- Repeated iteration
s = make_scores(iter([4, 1])) a, b = iter(s), iter(s) assert a is not b and next(a) == 4 and next(a) == 1 and next(b) == 4 and list(s) == [4, 1] and len(s) == 2 and repr(s) == "Scores((4, 1))"
- Source ownership
source = [3, 1] s = make_scores(source) source.append(9) assert type(s).__name__ == "Scores" and len(s) == 2 and list(s) == [3, 1] and sum(s) == 4 and repr(s) == "Scores((3, 1))" and source == [3, 1, 9]
- Consumer list independence
source = [8, 8] s = make_scores(source) view = list(s) view.clear() assert type(s).__name__ == "Scores" and len(s) == 2 and list(s) == [8, 8] and repr(s) == "Scores((8, 8))" and source == [8, 8] and view == []
Why not make Scores its own single iterator?
That would share cursor state and exhaust later traversals. A tuple snapshot plus a fresh iterator per request supports repeatable reads. Building n entries costs O(n) work and space; len is O(1), and a full traversal is O(n).
Cooperate with a binary operator
Return a two-component Vector value. Addition makes a new value; unsupported operand types must be declined with NotImplemented.
The contract
- x and y are integers. The returned object's type is named Vector with readable x and y.
- For two vectors produced by this factory, + returns a new Vector with component sums. Do not mutate either operand.
- For unsupported types, a direct __add__ call returns NotImplemented; normal + must raise TypeError when neither side handles the operation. Vectors from separate calls must interoperate.
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.
- Component sums and type
a, b = make_vector(2, 3), make_vector(4, -1) r = a + b assert type(a).__name__ == "Vector" and type(r) is type(a) and type(r.x) is int and type(r.y) is int and (r.x, r.y) == (6, 2)
- Zero boundary
a, b = make_vector(0, 0), make_vector(0, 0) r = a + b assert type(r) is type(a) and (r.x, r.y) == (0, 0) and r is not a and r is not b
- Repeated operand
a = make_vector(3, -2) r = a + a assert type(r) is type(a) and (r.x, r.y) == (6, -4) and (a.x, a.y) == (3, -2) and r is not a
- Unsupported sentinel
a = make_vector(1, 2) assert type(a).__name__ == "Vector" and (a.x, a.y) == (1, 2) and a.__add__(2) is NotImplemented and a.__add__((1, 2)) is NotImplemented
- Operator failure
a = make_vector(1, 2) try: a + 3 except TypeError: pass else: assert False, "unsupported addition accepted" assert type(a).__name__ == "Vector" and (a.x, a.y) == (1, 2) - Both operands preserved
a, b = make_vector(-2, 5), make_vector(7, 8) r = a + b r.x = 100 assert type(r) is type(a) and (r.x, r.y) == (100, 13) and (a.x, a.y) == (-2, 5) and (b.x, b.y) == (7, 8) and r is not a and r is not b
Why must the vector class be shared across factory calls in this solution?
A fresh local class per call would make a strict class-based operand check reject the other factory's vectors. One shared type keeps that contract precise. Addition performs constant-count arithmetic and allocates one fixed-field result, excluding arbitrary-size integer costs.
Transfer: expose only a selected sequence window
The requirement changes from all scores to a slice captured at construction. Support indexing, negative indices and slicing as well as repeatable iteration.
The contract
- values is a finite iterable of integers; start and stop are integer slice bounds and use normal Python [start:stop] semantics.
- Return an object with len, fresh iteration, and __getitem__. An integer index returns an int; a slice returns an exact tuple.
- Capture the selected sequence once and preserve order and repeats. Input edits cannot change it; out-of-range integer indices raise IndexError. No source mutation.
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.
- Selected protocol values
w = make_window([2, 4, 6, 8], 1, 3) assert type(len(w)) is int and len(w) == 2 and list(w) == [4, 6] and type(w[0]) is int and w[0] == 4 and w[-1] == 6 and type(w[:]) is tuple and w[:] == (4, 6)
- Empty window
w = make_window([], 0, 9) assert len(w) == 0 and list(w) == [] and type(w[:]) is tuple and w[:] == () try: w[0] except IndexError: pass else: assert False, "missing index accepted" - Repeated and negative bounds
w = make_window([9, 2, 2, 4], -3, 99) assert len(w) == 3 and list(w) == [2, 2, 4] and type(w[0]) is int and w[0] == 2 and type(w[::-1]) is tuple and w[::-1] == (4, 2, 2)
- Fresh cursors from iterator input
w = make_window(iter([1, 3, 5, 7]), 1, 4) a, b = iter(w), iter(w) assert a is not b and next(a) == 3 and next(b) == 3 and list(w) == [3, 5, 7] and len(w) == 3 and type(w[:2]) is tuple and w[:2] == (3, 5)
- Input ownership and returned tuple
source = [1, 3, 5] w = make_window(source, 0, 2) source[0] = 9 source.append(7) assert len(w) == 2 and list(w) == [1, 3] and type(w[:]) is tuple and w[:] == (1, 3) and source == [9, 3, 5, 7]
- Reversed bounds and out-of-range
w = make_window([2, 4], 2, 1) v = make_window([2, 4], 0, 2) assert len(w) == 0 and list(w) == [] and type(w[:]) is tuple and w[:] == () and len(v) == 2 and v[-1] == 4 try: v[2] except IndexError: pass else: assert False, "out-of-range index accepted"
Why delegate __getitem__ instead of manually handling negative indices?
The stored tuple already supplies coherent integer and slice rules, including exceptions. Construction costs O(n+k) work with an intermediate n-entry snapshot and a k-entry selection; retained storage is O(k). Length and integer indexing are O(1), while a returned slice copies its selected entries.
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 milestoneLookup is protocol-driven
Implicit special operations usually look on the type, not on the individual instance. Unsupported binary operands should often return NotImplemented so Python can try the reflected operation.
Understand first
Optional depth: patching one object's __len__ can mislead you if you assume all syntax is a direct attribute call. Binary operators also need to cooperate with other operand types.
Words you will see
- Implicit special lookup
- The type-based lookup used by operations such as len(obj).
- NotImplemented
- A sentinel returned to decline an unsupported binary operation.
- Reflected operation
- The other operand's chance to handle an operator, such as __radd__.
Normal access is not protocol dispatch
size.__len__() explicitly reads the instance attribute and calls its lambda, returning ninety-nine. len(size) instead consults Size.__len__ and returns two. Defining special methods on the class is the reliable way to implement a protocol.
Do not generalize this to every method call. Ordinary size.some_method lookup follows ordinary attribute rules. This distinction concerns implicit special operations and can be altered only through more advanced type-level behavior.
Decline without hiding errors
Point.__add__ accepts another Point and returns a new Point; neither operand is mutated. For a number it returns NotImplemented. With the + syntax Python can then try the other operand's reflected method, and if neither side supports the pair it raises TypeError.
NotImplementedError is an exception and does not request operator fallback. A direct __add__ call exposes the sentinel, as the example demonstrates; normal caller code should prefer +. Choose isinstance or an exact-type policy based on the value model and subclass behavior.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
size.__len__ = lambda: 99Install an instance attribute for explicit access only.
print(len(size))The length protocol still finds the class implementation.
return NotImplementedDecline the unsupported operand without raising here.
return Point(self.x + other.x)Create a result without updating either input point.
Special operations often look up methods on the type rather than following ordinary instance attribute lookup. Assigning a special method to one instance may not change len(instance). Return NotImplemented for unsupported operand types when appropriate, rather than confusing it with raising NotImplementedError.
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 protocol behavior at the type.
Try: Add Size.__len__ = lambda self: 4 before the prints.
The explicit call stays 99, but len(size) becomes 4.
Observe operator failure.
Try: Append print(Point(2) + 3).
TypeError is visible; no broad handler turns it into a guessed point.
Before you move on
What happens with Point(2) + 3 through operator syntax?
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
Neither Point nor int supports that pair, so Python raises TypeError after the available fallback attempts. The sentinel is not silently treated as a numeric answer.
Avoid surprising costs
Special methods should have predictable costs and effects. A value's equality and hash must agree, and mutable value-based objects usually should not be hashable.
Understand first
Optional depth: custom operators are useful only if callers can reason about them. A coordinate can be a stable dictionary key, but a changing collection should not pretend that its current value is a permanent identity.
Words you will see
- Hash
- An integer used to organize keys in hash-based containers.
- Value equality
- Comparing meaningful contents rather than object identity.
- Hash consistency
- Equal objects have equal hashes and a key's hash remains stable while stored.
Equality is not identity or uniqueness of hashes
The frozen dataclass generates field-based equality and a compatible hash for these integer fields. Two separately created coordinates compare equal, and the set retains one equal key. The final identity comparison is False.
Do not print or assert a particular hash integer as a portable example. Hash algorithms and some value hashes can differ across runs or versions. Equal hashes do not imply equal objects; containers also compare equality when resolving collisions.
Keep operators modest
A local tuple-backed length is predictable; a __len__ that contacts a remote service would surprise callers with delay and failure. This browser-local example does no I/O. Prefer explicit methods for expensive or effectful work.
Do not define ordering simply because equality exists: coordinates do not have one inevitable business ordering. Do not use unsafe_hash to make changing value fields into keys. If fields contained mutable unhashable objects, frozen=True alone would not make hashing work. Recap: protocol convenience must not hide unstable state or unexpected work.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@dataclass(frozen=True)Generate value methods while preventing normal field rebinding.
print(first == second)Compare matching coordinate fields.
print(hash(first) == hash(second))Test the equality/hash rule without asserting a particular hash number.
print(len({first, second}))Equal keys collapse to one set entry.
A __len__ that queries a remote service is legal but surprising. Document costs and side effects. Keep equality, ordering and hashing consistent, and do not implement rich operators merely to make domain code look clever.
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 the values different.
Try: Change second to Coordinate(2, 4).
Equality is False and the set has two entries; do not assume any particular unequal-hash result.
Try rebinding a key field.
Try: Append first.x = 9.
FrozenInstanceError is raised, preserving the normal immutable-value API.
Before you move on
If hash(a) == hash(b), must a == b?
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. Different values can collide. The required direction is that equal values must have equal hashes; the reverse is not guaranteed.
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.
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.