Annotations, unions and boundary validation
Use types to explain contracts without confusing them with runtime checks.
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 static types describe possible values
- Apply narrow before using
- Reason about version-sensitive typing
Static types describe possible values
An annotation describes an intended value for readers and checking tools. It is not a guard that stops the Python interpreter from accepting a different value.
Understand first
Use annotations when a function has several callers and a clear contract matters. Start with functions, return values and basic Python types. External data still needs explicit runtime checks, even when the receiving name has an annotation.
Words you will see
- Annotation
- A type description written after a colon or return arrow.
- Static checker
- A separate tool that analyses source without running the application.
- Runtime validation
- Code that inspects actual values while the program runs.
A promise and a gate do different jobs
The echo function promises an integer result, but returns its input unchanged. Passing a string is legal for the interpreter. A configured static checker should flag this call, while this runnable example deliberately demonstrates that execution alone does not enforce the promise.
The checked function adds a real gate: type(value) is int. That rejects strings and also bool, which is an int subclass. This exact-type rule is a policy choice, not a universal rule that every API should adopt.
Check at the boundary, then use a precise contract
The accepted value 4 is printed as an integer. The second print shows that the unguarded function accepted text. Validate inputs when reading a file or receiving a message, so invalid data fails near its source rather than during unrelated arithmetic.
For trusted internal callers, annotations plus a static checker can be enough; repeatedly rechecking every helper may obscure the logic. For external values choose explicit conversion only if the contract allows it. int('4') converts text, whereas the guard here rejects text. Neither choice should happen by accident.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def echo(value: int) -> int:State the intended parameter and return types without adding a runtime test.
return valueReturn the actual object supplied by the caller.
if type(value) is not int:Check an exact type, deliberately excluding bool.
print(type(echo('four')).__name__)Show the actual return type, str, rather than its promised annotation.
Annotations help tools and readers detect incompatible uses. Python does not enforce ordinary annotations at runtime. A function annotated to accept int still needs validation when its inputs come from HTTP, a file or another untrusted boundary.
Conceptual input boundary: documentation does not execute validation
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- DescribeAn annotation tells a reader which values are intended.
- InspectAn explicit condition checks the actual value at runtime.
- Accept or rejectOnly values passing the condition reach the trusted computation.
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.
Send text to the guarded function.
Try: Replace print(checked(4)) with print(checked('4')).
TypeError stops execution before later prints; no fallback output is invented.
Change the annotation only.
Try: Change echo's return annotation to str, leaving its body unchanged.
The displayed values do not change. A checker may report different static errors, but annotations do not execute the gate.
Before you move on
A fresh message supplies True as a count. Would checked accept it, and would an annotation alone reject it?
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
checked rejects it because type(True) is bool. The annotation alone does not reject anything at runtime; bool is also compatible with int in many static contexts, so the exact boundary rule must be documented.
Narrow before using
A union lets a value have one of several described types. A branch must establish which case is present before using a case-specific operation.
Understand first
Use an optional field when absence has a meaning distinct from empty text. A TypedDict can document the enclosing record while an exact None check narrows a trusted field inside it.
Words you will see
- Union
- A choice of described types, written with |.
- Optional value
- A value whose described possibilities include None.
- TypedDict
- A static field-shape description for an ordinary dictionary, not a runtime validator.
Name the absent case before computing
Event describes a name field containing str or None. display reads the field once. If it is None, the function returns '(absent)'; otherwise len can operate on the remaining string. The second fixture contains an empty string, so it produces length 0 rather than the absent label.
The exact None branch is important. if not value would group absent and empty text together and lose the distinction. Narrowing is both a useful static fact and ordinary executed control flow; no special runtime conversion happens.
Keep trusted records separate from external data
This helper assumes a present name key and a string-or-None value. TypedDict does not validate JSON, add a missing key or reject a number. An external boundary should check shape and values before calling display, as the optional boundary-validation depth explains.
Use a simple parameter rather than a record when there is only one field and no shared schema. Prefer a precise union to Any when callers need to handle absence. A default is not always suitable: an absent account identifier may need an error instead of display text.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
name: str | NoneDescribe two possible field kinds for static tools.
value = event['name']Read one trusted field without modifying its record.
if value is None:Take the absent branch only for the None singleton.
return str(len(value))Compute length only after ruling out None under the trusted union contract.
An optional result such as str | None requires a branch before string operations. Prefer a precise return contract over Any. TypedDict describes expected dictionary shapes to tools but does not validate parsed JSON automatically.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try a present value.
Try: Change the second fixture to {'name': 'oak'}.
The second output becomes 3; no record mutation occurs.
Expose the required key.
Try: Change the first fixture to {}.
KeyError surfaces. A union allowing None does not permit a missing required key.
Before you move on
For a fresh trusted record {'name': 'rain'}, what does display return and does it edit the record?
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 '4'. The value is not None, len reads four characters, and the original dictionary remains unchanged.
Narrow an optional input
Narrowing means using a condition to reduce the possible kinds of a value before using an operation that needs one kind.
Understand first
An optional name can be absent, represented by None. Test for absence before calling a string method. This gives tools a more precise view and gives the running program an actual safe branch.
Words you will see
- Union
- A type expression such as str | None allowing either kind of value.
- None
- The singleton value commonly used to represent absence.
- Narrowing
- Ruling out possibilities along a branch, such as excluding None.
Absence is not a blank string
The first call passes None, so the early return produces Hello, guest. The second passes a string with spaces. It skips the None branch, calls strip to remove outer whitespace, and inserts Ada into the greeting.
Use is None rather than if not name when absence alone should trigger the default. An empty string is false in a condition but is still a string. This function intentionally treats an empty or whitespace-only name as a present, blank name; a different product rule would need another check.
Choose the failure policy explicitly
The annotation str | None documents the two expected cases. It does not reject integer 7 at the boundary; 7 would later fail at strip with AttributeError. Add explicit shape validation when callers are untrusted rather than treating this helper as a complete parser.
Returning None, raising a specific exception, or providing a guest label are different APIs. Choose a default only if it preserves meaning. A guest label is reasonable for display but may be unsafe for an account identifier that must exist.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def greet(name: str | None) -> str:Describe a string-or-absence parameter and string result.
if name is None:Distinguish absence from an empty but present string.
return 'Hello, guest'Finish the absent case before any string method runs.
return f'Hello, {name.strip()}'Use the remaining string and remove only its outside whitespace.
The None branch narrows the value before calling strip. The annotation remains documentation/static evidence, not an input parser.
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.
Test a present blank name.
Try: Add print(repr(greet(' '))).
The representation shows 'Hello, ', proving that absence and blank text differ.
Change the default message.
Try: Replace 'Hello, guest' with 'Welcome, visitor'.
Only the None call changes. The string branch remains independent.
Before you move on
What greeting should a fresh call greet(' ') produce under this contract?
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 produces 'Hello, ' with a trailing space. The input is present, and strip turns it into an empty string. Rejecting blank names would be a new requirement, not an effect of the union.
Where this idea earns its place
Type annotations communicate a contract to readers and static tools; validation checks actual values arriving at runtime. Both are useful, but they operate at different boundaries. An API request, CSV row or environment string remains external data even when the receiving function has a precise annotation.
Follow the mechanism step by step
A type checker reasons about possible values along control-flow paths. A check for None can narrow str | None to str. A TypedDict describes expected mapping fields to the checker but does not parse JSON. At runtime, ordinary Python functions do not automatically enforce these annotations or reject extra fields.
Work through a concrete application
Parse external data into a validated domain shape, then pass that shape to typed internal functions. For a count, decide whether bool is acceptable, define bounds and reject malformed values explicitly. Keep a missing field distinct from a present None if the domain requires it. This reduces repeated defensive parsing inside every helper.
Failure cases and misleading shortcuts
Using Any everywhere can silence the very checks the annotations were intended to provide. Broad casts can assert a fact that was never established. Conversely, a type mismatch is not always a reason to coerce input automatically: converting an arbitrary object to a string may hide a bad request rather than validate it.
Cost, ownership and alternatives
Validation has an execution cost, so place comprehensive checks at trust boundaries and preserve clear internal invariants. Static analysis adds build-time feedback but cannot prove an external service always returns its documented response. Version-specific typing syntax must match the declared Python support range.
Verify the contract
Run the chosen static checker and runtime tests separately. Test missing fields, wrong types, oversized values and boundary limits. Include paths in which an optional value remains absent. A program executing successfully on one example does not prove its annotations are correct, and a passing checker does not prove its business rules.
Transfer question: Is object safer than Any for a value whose type is unknown?
It generally requires narrowing before type-specific operations, while Any permits many operations unchecked. Neither validates external data automatically. Use a parser or explicit checks to establish a useful domain type rather than keeping uncertainty throughout the application.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Narrow an optional input
Without copying the worked code, reproduce its observable contract: The None branch narrows the value before calling strip. The annotation remains documentation/static evidence, not an input parser. 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.
Guard an exact count
Accept only a nonnegative built-in int. Return it unchanged; reject bool, strings and negative values with ValueError.
The contract
- Input is any object; valid values are exact built-in nonnegative integers.
- Return the accepted integer without conversion; do not mutate any input.
- Raise ValueError for every other value, including bool. 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.
- ordinary
source = 7 result = validate_count(source) assert type(result) is int and result == 7 and source == 7
- zero
source = 0 result = validate_count(source) assert type(result) is int and result == 0 and source == 0
- large
source = 10 ** 30 result = validate_count(source) assert type(result) is int and result == 10 ** 30 and source == 10 ** 30
- boolean
source = True try: validate_count(source) except ValueError: pass else: assert False, 'expected ValueError' assert source is True - text
source = ['7'] before = source.copy() try: validate_count(source[0]) except ValueError: pass else: assert False, 'expected ValueError' assert source == before - negative
source = -1 try: validate_count(source) except ValueError: pass else: assert False, 'expected ValueError' assert type(source) is int and source == -1
Why not int(value)?
Conversion would accept text and bool, changing the strict contract. The solution uses a constant number of checks and no mutable storage; integer range comparison has the usual bounded-integer teaching cost.
Narrow optional names
Return a fresh list: None becomes 'guest'; strings are stripped, including blank strings becoming ''. Preserve positions and duplicates.
The contract
- Inputs are a list containing only strings or None; invalid other kinds are outside this helper's contract.
- Keep order and duplicates. Only None means guest; blank text remains blank.
- Return a fresh outer list and leave input unchanged. 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.
- mixed
source = [' Ada ', None] before = source.copy() result = display_names(source) assert type(result) is list and result == ['Ada', 'guest'] assert source == before and result is not source assert all(type(value) is str for value in result)
- empty
source = [] before = source.copy() result = display_names(source) assert type(result) is list and result == [] assert source == before and result is not source
- blank
source = ['', ' '] before = source.copy() result = display_names(source) assert type(result) is list and result == ['', ''] assert source == before and result is not source
- repeats
source = [None, None, ' x ', ' x '] before = source.copy() result = display_names(source) assert type(result) is list and result == ['guest', 'guest', 'x', 'x'] assert source == before and result is not source
- whitespace
source = ['\tLin\n'] before = source.copy() result = display_names(source) assert type(result) is list and result == ['Lin'] assert source == before and result is not source
- independent result
source = ['oak'] before = source.copy() result = display_names(source) assert type(result) is list and result == ['oak'] assert source == before and result is not source result.append('elm') assert source == ['oak']
Why is a truthiness default wrong?
It also turns empty strings into guest. This pass uses O(n) result slots and time proportional to all characters stripped as well as n elements.
Transfer: validate records before narrowing
The requirement changes: receive a list of untrusted records with exactly one 'count' field. Validate every record and return a fresh list of accepted integers.
The contract
- The outer input is a list; every element must be a dict with exactly count, an exact built-in nonnegative int.
- Reject an invalid record with ValueError. No partial result is returned; input records must never be edited.
- Keep order and duplicates in a fresh list. No conversion, network or file access.
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.
- records
source = [{'count': 2}, {'count': 0}, {'count': 2}] result = parse_counts(source) assert type(result) is list and result == [2, 0, 2] and all(type(x) is int for x in result) assert source == [{'count': 2}, {'count': 0}, {'count': 2}] and result is not source - empty
source = [] before = source.copy() result = parse_counts(source) assert type(result) is list and result == [] assert source == before and result is not source
- bool rejected
source = [{'count': True}] try: parse_counts(source) except ValueError: pass else: assert False, 'expected ValueError' assert source == [{'count': True}] - extra field
source = [{'count': 1, 'extra': 2}] try: parse_counts(source) except ValueError: pass else: assert False, 'expected ValueError' assert source == [{'count': 1, 'extra': 2}] - missing field
source = [{}] try: parse_counts(source) except ValueError: pass else: assert False, 'expected ValueError' assert source == [{}] - late invalid
source = [{'count': 3}, {'count': -1}] try: parse_counts(source) except ValueError: pass else: assert False, 'expected ValueError' assert source == [{'count': 3}, {'count': -1}]
Why is adding TypedDict not enough?
It does not execute these shape and domain checks. The loop uses O(n) result slots and time including every inspected record key; accepted records each have a fixed one-field shape.
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 milestoneBoundary validation must be explicit
Boundary validation checks a value's shape and allowed contents before the rest of the application relies on them.
Understand first
A TypedDict helps a checker understand field names, but a normal dictionary can still be malformed at runtime. Check shape, exact numeric policy and size before doing real work with incoming records.
Words you will see
- TypedDict
- A static description of keys and value types in an ordinary dictionary.
- Shape
- The allowed fields and arrangement of a record.
- Domain rule
- A meaning-based restriction, such as a count being nonnegative.
Validate structure before contents
The parse function first requires a dictionary with exactly the count key. Its short-circuit or prevents the set conversion for non-dictionaries. Only then does it read raw['count'], so a missing field does not cause an accidental KeyError.
The next condition rejects bool and negative integers. Value 0 remains valid because zero work is not absence. The return statement constructs a fresh dictionary: changing the returned count slot will not change the input dictionary.
Keep a deliberate boundary small
The Count annotation expresses the accepted shape to tools. The actual checks enforce this example's strict policy; they do not run because TypedDict exists. For larger schemas a dedicated validator may improve error reporting, but it is an optional dependency and is not installed here.
Rejecting extra keys catches accidental payload changes, while an extensible API may intentionally allow them. This small parser has constant field count; checking a supplied dictionary's keys takes work proportional to its number of fields. Real external payloads also need byte and nesting limits before decoding.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if not isinstance(raw, dict) or set(raw) != {'count'}:Reject a missing field, an extra field or a different outer container.
value = raw['count']Read only after establishing the key exists.
if type(value) is not int or value < 0:Reject bool, text and negative counts.
return {'count': value}Build a fresh one-field result rather than returning the caller's dictionary.
Decide whether bool is acceptable where an integer is expected, whether subclasses are allowed and whether extra fields are rejected. Validate shape and size before doing expensive work. A static type checker cannot prove what an external service will return.
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.
Exercise the strict numeric rule.
Try: Set source = {'count': True}.
The explicit exact-type guard raises ValueError rather than treating True as 1.
Check independent slots.
Try: After parsing add result['count'] = 5, then print(source).
source remains {'count': 0}; this example has no nested mutable fields to share.
Before you move on
Should {'count': 2, 'debug': False} pass this parser?
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 exact-key test rejects the extra debug field before the count is used. A permissive-extra-fields parser would be a different contract.
Version-sensitive typing
A typing feature has a Python-version requirement and may be useful to tools without changing runtime behaviour.
Understand first
A team must agree on its oldest supported interpreter and run a checker separately. get_type_hints can inspect annotations, but inspection is not validation and should not evaluate untrusted annotation text.
Words you will see
- Baseline
- The oldest interpreter version an example or application supports.
- Type hint
- An annotation intended to describe types to readers and tools.
- Introspection
- Reading information about a running object, such as its annotations.
Read annotations without confusing their purpose
The total function expects a list of integers and returns sum(values). get_type_hints resolves its trusted local annotations, and the two prints compare them with expected type objects. Both comparisons are True; no values have been validated by that inspection.
list[int] is supported on modern Python, and this batch targets 3.11 or newer. Newer syntax such as type parameter lists needs a newer baseline and must not be pasted into a 3.11 editor without warning. Annotation evaluation details can also vary by Python version.
Keep checker evidence separate
The runtime result 5 comes from adding two integers, not from asking for type hints. A static checker can flag incompatible uses before execution, but requires configuration, dependency stubs and an explicit command. This browser example does not pretend to run that tool.
Prefer simple annotations when they capture the real contract. Any is sometimes necessary at a dynamic boundary, but spreading it removes useful diagnostics. object keeps the requirement to narrow before type-specific operations; it is not an alias for Any.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def total(values: list[int]) -> int:Use built-in generic notation available on the supported baseline.
return sum(values)Compute a value with ordinary Python operations.
hints = get_type_hints(total)Read annotations from this trusted local function.
print(hints['return'] is int)Compare a resolved annotation with the intended type object.
Some syntax and typing features require newer Python versions. Keep the course's baseline and optional newer features labelled. Run a selected static checker in CI; examples that execute successfully do not demonstrate static correctness by themselves.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change the data without changing types.
Try: Replace [2, 3] with [].
The hint comparisons remain True and total returns 0.
Compare another annotation.
Try: Change the first comparison to hints['values'] == list[str].
It prints False; inspection reveals the declared element type, not a runtime sample.
Before you move on
Would inspecting a fresh function annotated list[str] prove that every future list contains strings?
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. Introspection only reads its declared contract. Runtime guards or a parser must inspect actual external elements, while a separate checker analyses typed callers.
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.