Generics, protocols and typed callables
Express reusable relationships without erasing useful information.
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 preserve relationships between types
- Apply protocols express structural contracts
- Reason about variance and api design
Preserve relationships between types
A typed callable describes a function-shaped dependency: which arguments it accepts and what result it returns.
Understand first
Pass behaviour in when the traversal stays the same but the transformation changes. A type variable can connect an input list's element type to the callable parameter and a second variable to its result type.
Words you will see
- Callable
- A value that can be invoked, such as a function.
- Callback
- A callable supplied for another function to invoke.
- Eager result
- A result fully computed before the function returns.
Keep traversal and transformation separate
map_values loops over values in their original order and calls fn once per element. A list comprehension collects a fresh outer list. T describes each input element; U describes the corresponding callback result. The function can therefore map integers to strings without claiming the output still contains integers.
The sample transforms 2 and 4 to 'n=2' and 'n=4'. It prints the unchanged source afterward. A fresh outer result does not mean callbacks are harmless: a callback receiving a mutable object could still mutate that shared element.
Choose eager or lazy evaluation
An eager list is easy to inspect and repeat, but retains all results. Built-in map returns an iterator and delays callback execution until consumption. Choose intentionally because errors and side effects then happen at different times.
For n elements this wrapper makes n callback calls and allocates n result slots. Total time also includes callback work; it is not simply O(n) if each callback scans a growing collection. Type hints cannot prove that a callback is pure, fast or deterministic.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
U = TypeVar('U')Keep result elements independent from input element types.
return [fn(value) for value in values]Invoke in order and collect a new outer list.
source = [2, 4]Keep a named input so preservation can be observed.
print(source)Show that this pure callback left the caller's list unchanged.
A generic function can describe that its return type follows its input element type. Replacing every type with object or Any loses different information: object requires narrowing, while Any disables many checks. Use a type variable when the relationship is real.
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 only the operation.
Try: Use lambda value: value * 10 in the map_values call.
The output becomes [20, 40]; source stays [2, 4].
Prove empty traversal.
Try: Set source = [].
No callback runs and both printed lists are empty.
Before you move on
For fresh input [1, 1, 2], how many callback calls should this eager mapper make?
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
Three, including both repeated ones. Traversal preserves positions and duplicates rather than deduplicating values.
Protocols express structural contracts
A protocol states what a consumer needs to use, not which family an implementation must inherit from.
Understand first
Two unrelated objects can supply the same method. This is useful at adapter boundaries where tests use a small in-memory implementation and the application later uses a real adapter.
Words you will see
- Protocol
- A static interface expressed as required attributes and methods.
- Consumer
- Code that uses an interface without constructing its implementation.
- Adapter
- An object that offers the expected operations over a different implementation.
Ask for one small capability
Readable requires a read method with no arguments returning str. preview calls it once and uppercases the result. Memory has the required method but no inheritance from Readable. Its value is constructor state, so each instance can hold a different fixture.
The two objects produce API and QUEUE independently. The protocol is a description for checking tools, while ordinary attribute lookup and method calls make the program run. A missing read method still raises AttributeError at runtime.
Structure is smaller than semantics
A network reader with the same method name could block, fail or consume state. Those behaviours are not captured by the return annotation. Document whether reads are repeatable and write tests for side effects, errors and ownership.
Use an ordinary function parameter when one callable is enough. Use an abstract base class when shared implementation or explicit registration is needed. A narrow protocol is often easier to implement than a large interface containing unrelated methods.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
class Readable(Protocol):Declare the small capability for tools.
def read(self) -> str: ...Describe a method signature, not a working reader.
return self.valueSupply the behaviour in the concrete in-memory implementation.
return source.read().upper()Use the capability once and transform its result.
A protocol describes required operations without forcing inheritance from a concrete base. It helps decouple a consumer from a specific implementation. Static structural compatibility does not replace behavioural tests such as ordering, exceptions or side effects.
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 one instance.
Try: Replace Memory('api') with Memory('disk').
Only the first printed label becomes DISK; the instances own separate values.
Observe a missing capability.
Try: Replace Memory('queue') with object().
AttributeError surfaces at read. The annotation adds no runtime guard.
Before you move on
A fresh adapter read() clears its buffer. Does structural compatibility prove two preview calls match?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It may satisfy the signature yet have consuming behaviour. Document that behaviour and use a repeated-call test if repeatability is part of the consumer's needs.
Depend on a behaviour
A generic function keeps a useful type relationship while working with more than one element type.
Understand first
Use a type variable when the result type genuinely follows an input type. A read-only Sequence is enough when a function only reads an indexed element. Knowing indexing and exceptions helps explain the empty-input policy.
Words you will see
- Generic
- A definition parameterised by a type relationship.
- Sequence
- An interface supporting ordered indexed reading, such as a list or tuple.
- Structural contract
- Required operations, without requiring inheritance from one concrete class.
One relationship, not one concrete class
T connects the element type of values to first's return type. With integer input the expected result type is integer; with string input it is string. Replacing T everywhere with object would lose this connection for callers.
The body still reads position zero and raises IndexError for an empty sequence. A type variable does not create an empty-case policy. The sample then introduces Named, a protocol saying that a readable name attribute is required.
Describe behaviour at the interface
Service never inherits Named, yet it supplies name. label reads that attribute and uppercases its string. Static structural compatibility allows such consumers to avoid depending on a concrete Service class.
A protocol does not check every runtime object or promise that reading a property is side-effect-free. Test behaviour independently. If first should support arbitrary single-pass iterators, change the interface and implementation deliberately; indexing a generator is not possible.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
T = TypeVar('T')Introduce a relationship variable for static tools.
return values[0]Return the original first element, not a converted copy.
name: strDescribe the attribute expected by the Named protocol.
return value.name.upper()Read the supplied object's behaviour without requiring Service inheritance.
The example preserves the sequence element relationship and uses a structural name contract. An empty sequence still needs a documented error policy.
Conceptual generic relationship, not runtime conversion
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- InputSequence[T] describes elements of one related type.
- ReadIndex zero returns an existing element without changing it.
- OutputThe returned T preserves the relationship; emptiness still needs a policy.
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 another element type.
Try: Replace first([3, 5]) with first(['oak', 'elm']).
The value becomes oak, with no conversion added.
Explore the empty boundary.
Try: Replace [3, 5] with [].
IndexError is visible. Generic typing does not invent a default.
Before you move on
For a fresh call first(('red', 'blue')), what is returned and is a new tuple created?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It returns the string 'red'. Indexing reads the existing element; first does not build a tuple or copy the element.
Where this idea earns its place
Reusable APIs often need to preserve a relationship rather than accept one concrete type. A function returning the first element should preserve the sequence's element type. A formatter consumer may need only a formatting operation, not inheritance from a specific implementation. Generics and protocols express those two forms of abstraction.
Follow the mechanism step by step
A type variable relates positions in a signature, while a protocol lists structural capabilities. A class can satisfy a protocol without explicitly inheriting from it when its shape matches. This does not establish semantic properties such as idempotency, ordering or non-mutation; those remain behavioural contracts.
Work through a concrete application
For first(values), accept an appropriate read-only sequence interface and state the empty-input policy. For a service dependency, define the smallest operations the consumer requires. Then write contract tests against multiple implementations so a structurally compatible object with different failure behaviour cannot silently violate expectations.
Failure cases and misleading shortcuts
Mutable containers introduce variance constraints because consumers may insert new values. Replacing a type variable with Any discards useful relationships. wraps preserves metadata, but typed decorators may need ParamSpec to preserve parameter relationships; neither typing construct repairs incorrect runtime forwarding.
Cost, ownership and alternatives
An abstraction has a maintenance cost when it is broader than actual use. Prefer a small protocol to a large interface requiring unused methods. Use read-only types when mutation is not needed, and retain concrete types inside implementation details where generality would only obscure the algorithm.
Verify the contract
Test generic behaviour with more than one element type and include an empty input. Run static-checker examples for valid and invalid substitutions. For protocols, verify observable behaviour, exceptions and ownership in addition to method presence. Avoid claiming runtime_checkable performs full type-signature or behavioural validation.
Transfer question: Why might Sequence be a better input contract than list?
If the function only reads ordered values, Sequence permits other suitable implementations and avoids promising list-specific mutation. If the function must append or replace items, that read-only contract is insufficient and the required mutable operations should be explicit.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Depend on a behaviour
Without copying the worked code, reproduce its observable contract: The example preserves the sequence element relationship and uses a structural name contract. An empty sequence still needs a documented error policy. 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.
Keep the first-element relationship
Return the original first element of a list or tuple; when empty, return the supplied default object. Never copy or mutate elements.
The contract
- Input is an indexed list or tuple and any default object. Empty input returns that exact default.
- Nonempty input returns the identical first element, not a converted or copied object.
- No mutation, no I/O. False, zero and None are valid present first elements.
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.
- integer
source = [3, 8] result = first_or(source, 9) assert type(result) is int and result == 3 and result is source[0] and source == [3, 8]
- empty identity
source = [] fallback = {'tags': []} result = first_or(source, fallback) assert type(result) is dict and result is fallback and result == {'tags': []} and source == [] - tuple
source = ('oak', 'elm') result = first_or(source, 'guest') assert type(result) is str and result is source[0] and result == 'oak' and source == ('oak', 'elm') - false is present
source = [False, True] result = first_or(source, True) assert type(result) is bool and result is False and source == [False, True]
- nested identity
first = [] source = [first, [2]] result = first_or(source, {}) assert type(result) is list and result is first and result == [] and source[0] is first and source[1] == [2] - none is present
source = [None] result = first_or(source, 'guest') assert type(result) is type(None) and result is source[0] and source == [None] fallback = False assert first_or([], fallback) is fallback
How would a type variable help?
It can relate sequence elements and the default to the result rather than erasing all types with Any. The body uses O(1) indexed reads and extra storage under ordinary list/tuple access assumptions.
Consume a name capability
Return uppercased names of supplied objects in order. The objects need only a string .name attribute, not a particular base class.
The contract
- Input is a list of objects with readable string name attributes. No inheritance requirement.
- Return a fresh list of strings in input order, retaining duplicates and empty names.
- Read each name without changing objects or the outer list. No I/O.
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.
- normal
from types import SimpleNamespace source = [SimpleNamespace(name='api'), SimpleNamespace(name='db')] result = labels(source) assert type(result) is list and result == ['API', 'DB'] and result is not source assert [x.name for x in source] == ['api', 'db']
- empty
source = [] before = source.copy() result = labels(source) assert type(result) is list and result == [] assert source == before and result is not source
- unrelated implementation
class Local: name = 'queue' item = Local() source = [item] result = labels(source) assert type(result) is list and result == ['QUEUE'] and result is not source assert source[0] is item and item.name == 'queue' - repeated reference
from types import SimpleNamespace item = SimpleNamespace(name='x') source = [item, item] result = labels(source) assert type(result) is list and result == ['X', 'X'] and result is not source assert source[0] is source[1] is item and item.name == 'x'
- empty name
from types import SimpleNamespace source = [SimpleNamespace(name='')] result = labels(source) assert type(result) is list and result == [''] and result is not source and source[0].name == ''
- no trimming
from types import SimpleNamespace source = [SimpleNamespace(name=' api ')] result = labels(source) assert type(result) is list and result == [' API '] and result is not source and source[0].name == ' api '
Does a protocol guarantee no side effects?
No. A property could do work when read. This contract promises behaviour for supplied readable names; uppercasing costs time proportional to total text length and allocates result strings plus O(n) outer slots.
Transfer: inject arbitrary transformation
Instead of reading names, accept a callable and apply it once per input element in order. Preserve returned object identity and propagate callback failures.
The contract
- Input is a list and a callable; call it exactly once for each position, including repeats.
- Return a fresh result list in the same order, preserving each callback result object without conversion.
- Do not mutate the outer input. Callback side effects remain the callback's responsibility; propagate its errors. No I/O in this wrapper.
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.
- change type
source = [2, 4] before = source.copy() result = apply_each(source, str) assert type(result) is list and result == ['2', '4'] assert source == before and result is not source assert all(type(x) is str for x in result)
- empty no calls
source = [] calls = [] result = apply_each(source, lambda x: calls.append(x)) assert type(result) is list and result == [] and result is not source and source == [] and calls == []
- duplicates call order
source = [2, 2, 1] calls = [] def transform(value): calls.append(value) return value * 10 result = apply_each(source, transform) assert type(result) is list and result == [20, 20, 10] and result is not source assert source == [2, 2, 1] and calls == [2, 2, 1] - returned identity
source = [0, 1] objects = [[], {}] result = apply_each(source, lambda index: objects[index]) assert type(result) is list and result == [[], {}] and result is not source assert result[0] is objects[0] and result[1] is objects[1] and source == [0, 1] - none callback result
source = [1] before = source.copy() result = apply_each(source, lambda x: None) assert type(result) is list and result == [None] assert source == before and result is not source
- error propagation
source = [1, 2] calls = [] def bad(value): calls.append(value) raise ValueError('fixture') try: apply_each(source, bad) except ValueError: pass else: assert False, 'expected ValueError' assert source == [1, 2] and calls == [1]
Why not catch errors and return None?
That replaces a failed transformation with valid-looking data and violates propagation. The wrapper uses O(n) result slots and n calls, plus the total cost and storage of the callbacks.
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 milestoneCallable wrappers
Typing a forwarding wrapper means preserving the relationship between its accepted arguments and the result it returns.
Understand first
Decorators often hide a function behind another function. ParamSpec describes the argument relationship to tools, while TypeVar describes the return relationship. The wrapper must still forward actual arguments correctly.
Words you will see
- ParamSpec
- A type variable representing a callable's parameter list.
- TypeVar
- A variable relating types across inputs and outputs.
- wraps
- A helper that copies function metadata; it does not enforce forwarding.
Preserve types and execute forwarding separately
P stands for the original parameters and R for the original result. Callable[P, R] states the relationship at the wrapper boundary. The inner function accepts positional and named arguments using *args and **kwargs and forwards both to fn.
The counted wrapper appends one marker for each actual call. Calling add(2, right=3) supplies one positional argument and one keyword. The forwarded function returns 5; the wrapper returns that same result rather than discarding it.
Metadata is not proof of behaviour
wraps makes the exposed name add instead of inner. It does not repair an omitted **kwargs, a missing return or a duplicated call. Those are runtime bugs even if a copied name and documentation look correct.
This syntax works on Python 3.11 and uses only typing and functools. A plain explicit wrapper with a fixed signature is simpler when only one function is wrapped. Static checker tests are separate from these execution examples; running this program does not run a type checker.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
P = ParamSpec('P')Name a parameter relationship, not an input value.
@wraps(fn)Copy the original function's public metadata.
return fn(*args, **kwargs)Forward both argument kinds exactly once and keep the result.
print(add(2, right=3))Exercise a keyword-only parameter through the wrapper.
ParamSpec can preserve parameter relationships through typed decorators; a TypeVar models the return relationship. Do not advertise a wrapper as signature-safe solely because wraps copied metadata. Static checking and runtime forwarding are separate checks.
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.
Count two calls.
Try: Add another print(add(1, right=1)) before the final print.
The final count becomes 2; there is one marker per call.
Expose missing forwarding.
Try: Remove **kwargs from the call to fn only.
The keyword-only right argument is lost and TypeError surfaces. The wrapper does not silently recover.
Before you move on
If a fresh wrapped function returns None intentionally, should inner manufacture a result?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. R also permits a None return relationship. A transparent wrapper returns exactly what the original function returns and records just its own documented side effect.
Variance and API design
Read-only interfaces permit safe reuse that writable containers may not. A function's permission to write matters as much as its permission to read.
Understand first
A list of dogs cannot safely be treated as a general writable list of animals if a caller can append a cat. Sequence lets a consumer read without granting that write operation.
Words you will see
- Variance
- Rules describing when related element types permit related container substitutions.
- Invariant
- A mutable generic usually cannot substitute a different element type merely because the element types are related.
- Read-only interface
- An interface exposing reading, not a guarantee that the underlying object can never change.
Restrict what the consumer can do
names accepts a Sequence of Animal and only reads each name. Dog inherits Animal, so dog objects support the needed read operation. The function builds a new list of strings and does not append another animal to dogs.
The second print confirms that the original list still has one element. At runtime Sequence annotations do not freeze the input. Another owner can still mutate a passed list, and a type checker can only reason about the operations described by typed code.
Explain the unsafe alternative
If a helper accepted list[Animal] and appended an unrelated Animal, treating list[Dog] as that writable list would allow non-dogs into a list that callers expect to contain dogs. Invariance prevents this unsound substitution in static analysis.
Use Sequence for ordered reading, Iterable for a single pass without indexing, and list only when list mutation is part of the contract. Do not silence a real mismatch with cast unless the missing evidence is supplied elsewhere and documented. A shallow read-only interface does not freeze nested objects.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
class Dog(Animal):Establish that a dog supports the animal interface.
def names(values: Sequence[Animal]) -> list[str]:Ask only for ordered reading, not list writes.
return [value.name for value in values]Read names into an independent result list.
print(len(dogs))Observe that this consumer did not change the outer list.
Mutable containers can make apparently safe substitutions unsound because consumers may write new values. Prefer read-only interfaces such as Sequence when mutation is not required. Explain constraints rather than silencing a checker with broad casts.
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 outer sequence.
Try: Replace dogs = [Dog('Pip')] with dogs = (Dog('Pip'),).
The outputs stay the same because names only reads.
Check shared object mutability.
Try: After the first print add dogs[0].name = 'Moss' and print(names(dogs)).
The new name appears. Reading through Sequence did not freeze the animal.
Before you move on
If a fresh caller passes a tuple of two dogs, does names need to change?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The function only iterates and reads attributes, so the tuple supports what it uses. A helper that appends would need a different interface and contract.
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.