Type Hints, Protocols, and Pattern Matching
Express type relationships and follow a structural pattern match.
python, typing, generics, protocols, pattern matchingTypes describe a relationship
Type hints help readers and static analysis tools understand a contract. Python does not automatically reject a call that violates a hint. A generic function can preserve a relationship between types, and a protocol describes the operations an object must provide without requiring inheritance.
Python illustration
from typing import Protocol, TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]
class Named(Protocol):
name: str
def describe(event: object) -> str:
match event:
case {"kind": "read", "pages": int(pages)} if pages > 0:
return f"Read {pages} pages"
case _:
return "Unsupported event"
print(first(["Ada", "Lin"]))
print(describe({"kind": "read", "pages": 3}))
print(describe({"kind": "read", "pages": -1}))
Prepared output — not live execution:
Ada
Read 3 pages
Unsupported event
The generic first expects a nonempty list and returns an element of the
same static type. Named describes an object with a string name; a class
need not inherit it to satisfy a type checker.
See the reasoning
Follow the match and guard
See why a negative page count reaches the fallback. This is a prepared demonstration, not live code execution.
Inspect the mapping
- Inputkind: read; pages: -1Current focus
- Patternnot yet tested
- Guardnot yet tested
- Resultpending
The input has kind read and an integer pages value.
Patterns and limits
match examines cases in order. The mapping pattern above allows extra
keys; int(pages) accepts an instance of int, including bool, because
bool is an int subclass. If booleans are invalid, check explicitly.
The guard pages > 0 is separate from the structural pattern. A bare name
in a pattern captures a value rather than comparing to a variable of that
name; use a qualified constant for a value comparison.
Protocols express structural expectations to static tools. Even
@runtime_checkable protocol checks are limited and do not validate
method signatures or data semantics. Validate untrusted input at runtime.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
