Unit 7 of 9 · about 3 hours · explain, implement

Type hints, generics, protocols and narrowing

Typed boundaries are the foundation of the next section. Hints are documentation the machine checks.

You'll be able to

  • Write PEP 695 generics and type aliases, and explain deferred annotation evaluation on Python 3.14.
  • Define a Protocol and contrast structural with nominal subtyping, including runtime_checkable limits.
  • Narrow unions with isinstance and assert_type, and pass mypy clean on a typed module.

Covers

Type hints, unions, generics, protocols and narrowing
1

Read

In this order, only the parts listed

0 of 6 done

  1. Type parameter listsPython language reference

    Sections 8.10 to 8.10.3: generic functions, classes and aliases since Python 3.12 by PEP 695; bounds, constraints and defaults

  2. Annotation scopes and lazy evaluationPython language reference

    Sections 4.2.3 and 4.2.4: annotation scopes; lazy evaluation since 3.12, extended to all annotations in 3.14 by PEP 649 and PEP 749

  3. Protocolstyping - type hints and protocols

    Protocols: structural subtyping; runtime_checkable limits (isinstance checks presence only)

  4. Genericstyping - type hints and protocols

    Generics: TypeVar-based generics for reading older code; write new code with the PEP 695 syntax above

  5. Checked narrowingtyping - type hints and protocols

    assert_type: ask the checker to prove a narrowed type at a program point

  6. mypy Type CheckerAlgoMaster Python - structured revision

    The mypy Type Checker lesson and its exercise; verify every syntax claim against the 3.14 sections above, since older examples may predate PEP 695

2

Focus on

  • Annotations are lazily evaluated since 3.14 by PEP 649: def f(x: 1/0) defines fine and fails only when __annotations__ is read. get_type_hints evaluates them in the right scope.
  • PEP 695 in 3.12 puts type parameters in brackets: def first[T](xs: list[T]) -> T. Read old TypeVar code; write the new syntax.
  • A Protocol defines structure, not lineage. isinstance against a non-runtime_checkable Protocol raises TypeError; a runtime_checkable check tests member presence only.
  • Narrowing proves a type at a point: isinstance branches plus assert_type as the checkable claim. isinstance with a parameterized generic raises TypeError.
Common mistakes · 3
  • Checking with isinstance(x, list[int]). Parameterized generics are not valid isinstance targets.
  • Treating a runtime_checkable Protocol as a full interface check. It verifies member presence, never signatures or semantics.
  • Assuming annotations run at def time. On 3.14 a ZeroDivisionError inside an annotation waits until someone reads it, which delays import-time failures.
3

Try it yourself

Closed-book, before checking anything

Closed-book, type a generic first() plus a small Protocol and a narrowing function over int | str; run mypy 2.4.0 clean. Show that def f(x: 1/0) defines without error on 3.14 and raises only on annotation access.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.def f(x: 1/0) -> None: pass runs without error on 3.14. When does it fail, and which PEP changed this?Answer

    It fails when __annotations__ is read, through the lazy __annotate__ hook. PEP 649 made annotations lazily evaluated in 3.14.

  2. 2.What does isinstance([], list[int]) do, and what should you write instead?Answer

    It raises TypeError: parameterized generics are not valid isinstance targets. Check isinstance(x, list) and narrow items separately, or use assert_type for the static claim.

  3. 3.class P(Protocol): def m(self) -> int. What does isinstance(obj, P) do without @runtime_checkable?Answer

    It raises TypeError. Structural checks need @runtime_checkable, which then checks member presence only.

  4. 4.Rewrite class Box(Generic[T]) with 3.12 syntax and state the minimum version.Answer

    class Box[T]: ... needs Python 3.12 or later by PEP 695.

5

Practice

You're done when

Your typed module passes mypy clean, your Protocol accepts an unrelated matching class, and you can state exactly when each annotation evaluates.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 5 more in the section
  • Python language referencePython Software Foundation · required

    Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.

  • AlgoMaster Python - structured revisionAlgoMaster · support

    Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.

  • typing - type hints and protocolsPython Software Foundation · reference

    Read Protocols for structural typing and runtime_checkable limits, Generics for TypeVar generics, and assert_type for narrowing checks. Use for the Protocol and narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.

Also in this section

  • Stas' Python Cookbook - selected pathStas Bekman · primary

    Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.

  • Packaging Python ProjectsPython Packaging Authority · required

    Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.

  • dataclasses - data classesPython Software Foundation · reference

    Read the @dataclass parameters (eq, order, frozen, slots), field() with default_factory, frozen instances, post-init processing, replace, asdict and astuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses.

  • gc - cycle garbage collectorPython Software Foundation · reference

    Read the cycle collector interface: collect, get_count, garbage and disable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs.

  • weakref - weak referencesPython Software Foundation · reference

    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.