Advanced Type Hints
Published by Brayan K
Advanced type hints let you describe flexible, reusable, and precisely-shaped types — generics, structural protocols, and typed dictionaries — that static checkers verify before your code ever runs.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Preserve the relationship between input and output
An annotation can say more than “some object comes back.” If a function selects one item from its input, its result should retain that item type. A TypeVar names the relationship. It is not a request to convert values, and it need not represent the same type across every call.
from collections.abc import Sequence
from typing import TypeVar, assert_type
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
if not items:
raise ValueError("first needs at least one item")
return items[0]
number = first([8, 13])
word = first(["tea", "coffee"])
assert_type(number, int)
assert_type(word, str)
print(number + 1)
print(word.upper())
# ✅ Expected output:
# 9
# TEASequence[T] asks for a readable sequence, so lists and tuples can both be used. assert_type asks a static checker to verify the inferred type; at runtime it returns its value unchanged. The browser runs the program but does not run a static checker. Basic annotations, unions, and checker setup belong to Type Hints & Static Typing with MyPy.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
if not items:
raise ValueError("first needs at least one item")
return items[0]
first([])
# ✅ Expected error:
# ValueError: first needs at least one itemThe function needs an explicit empty-input policy even with perfect annotations. A checker can track an element type without proving that a sequence contains an element. These examples use the TypeVar/Generic spelling available throughout Python 3.11–3.14; the newer type-parameter syntax requires Python 3.12 or later.
Read the newer spelling without breaking older Python
Python 3.12 added type parameters directly to function and class definitions. For example, def first[T](items: Sequence[T]) -> T: declares a type parameter scoped to that definition, rather than referring to a separately assigned TypeVar. A generic class can start with class Box[T]: instead of inheriting from Generic[T].
The statement type Vector = list[float] creates a type alias using the newer syntax. It names a type expression; it does not construct a list of numbers. Python 3.11 cannot parse these spellings, so the runnable examples keep the older compatible forms. Choose the syntax your project's minimum Python version supports, and configure your static checker to that same version. Both spellings express contracts for a checker, not input validation.
A generic container keeps one type per annotated instance
from typing import Generic, TypeVar, assert_type
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def get(self) -> T:
return self.value
box: Box[int] = Box(12)
assert_type(box.get(), int)
print(box.get() * 2)
# ✅ Expected output:
# 24For this annotation, assigning a string to box.value is a static type mismatch. Python still permits the assignment at runtime. Mutable containers cannot generally substitute a wider element type safely: code allowed to put any object into a container could corrupt one whose caller expects only integers. When a consumer only reads, accepting Sequence[T] can express that narrower requirement without granting mutation.
from typing import cast
text = "12"
promised = cast(int, text)
converted = int(text)
print(type(promised).__name__, type(converted).__name__)
print(promised is text)
# ✅ Expected output:
# str int
# Truecast tells the checker to trust your claim. It neither parses text nor validates input. Use a real conversion or validation at the data boundary; save casts for facts you have established by other means and the checker cannot infer.
Protocols describe capabilities without requiring a parent class
A function that needs one operation should say which operation it needs. A Protocol defines the method signature. An ordinary class can satisfy it structurally, meaning by having compatible members, without inheriting from it.
from typing import Protocol
class Labelled(Protocol):
def label(self) -> str: ...
class Parcel:
def label(self) -> str:
return "fragile"
class Folder:
def label(self) -> str:
return "reports"
def display(item: Labelled) -> str:
return item.label().upper()
print(display(Parcel()))
print(display(Folder()))
# ✅ Expected output:
# FRAGILE
# REPORTSA class with label(self) -> int does not satisfy this contract for a static checker, even though the method name matches. Adding @runtime_checkable makes some isinstance checks possible, but those checks do not validate parameter or return types.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Labelled(Protocol):
def label(self) -> str: ...
class WrongLabel:
def label(self) -> int:
return 7
item = WrongLabel()
print(isinstance(item, Labelled))
print(type(item.label()).__name__)
# ✅ Expected output:
# True
# intThe runtime result is deliberately not a validation strategy. Code that needs external data to have a particular type must check that data. Abstract base classes impose different inheritance/instantiation rules; see Abstract Base Classes (abc) when that is the contract you need.
TypedDict describes required keys; it does not create them
from typing import NotRequired, TypedDict
class Profile(TypedDict):
name: str
nickname: NotRequired[str | None]
missing: Profile = {"name": "Asha"}
empty: Profile = {"name": "Bea", "nickname": None}
print("nickname" in missing, "nickname" in empty)
print(missing.get("nickname"), empty.get("nickname"))
print(type(missing).__name__)
# ✅ Expected output:
# False True
# None None
# dictA NotRequired key may be absent. A required key whose value is str | None must still be present; it may store None. This distinction matters for an update request: omission might mean “leave unchanged,” while an explicit null might mean “clear it.” The domain decides that meaning. get alone cannot distinguish those cases.
from typing import NotRequired, TypedDict
class Profile(TypedDict):
name: str
nickname: NotRequired[str]
profile: Profile = {"name": "Asha"}
print(profile["nickname"])
# ✅ Expected error:
# KeyError: 'nickname'Check key membership before indexing an optional field, or choose an explicit fallback. A TypedDict instance is a normal dictionary at runtime; it does not validate a decoded JSON response. For input checking with a separate library, use Data Validation with Pydantic.
Complete a contract that does not discard useful information
Fill in the type variable returned by last and the key marker for a field that may be absent. The test call uses integers, but the function must also accept strings without changing its definition.
from collections.abc import Sequence
from typing import NotRequired, TypeVar, TypedDict
T = TypeVar("T")
def last(items: Sequence[T]) -> ___:
if not items:
raise ValueError("last needs at least one item")
return items[-1]
class Delivery(TypedDict):
address: str
note: ___[str]
delivery: Delivery = {"address": "Library"}
print(last([2, 5]))
print(delivery.get("note", "no note"))
# 👉 replace ___ with T
# 👉 replace ___ with NotRequired
# ✅ Expected output:
# 5
# no noteDescribe a receipt source and handle a missing note
Define a receipt dictionary with required integer total and optional string note. Define a protocol with a receipt() method returning that dictionary. Write a formatter accepting the protocol and a simple class that satisfies it without inheritance. The formatter should include a fallback for a missing note. Run it once with a note and once without one.
from typing import NotRequired, Protocol, TypedDict
class Receipt(TypedDict):
total: int
note: NotRequired[str]
class ReceiptSource(Protocol):
def receipt(self) -> Receipt: ...
class Order:
def __init__(self, total: int, note: str | None = None) -> None:
self.total = total
self.note = note
def receipt(self) -> Receipt:
result: Receipt = {"total": self.total}
if self.note is not None:
result["note"] = self.note
return result
def format_receipt(source: ReceiptSource) -> str:
receipt = source.receipt()
note = receipt.get("note", "no note")
return f"{receipt['total']} pence; {note}"
print(format_receipt(Order(500, "collect")))
print(format_receipt(Order(300)))
# ✅ Expected output:
# 500 pence; collect
# 300 pence; no noteUse a static checker on the complete program as well as running it. Changing the returned total to a string should be rejected by that checker; the interpreter itself will not enforce the dictionary annotation. The typing reference distinguishes these static contracts from runtime checks.
Practice quiz
A function takes Sequence[T] and returns T. What useful relationship does this express?
- Every call must use one global type
- The result retains the input element type
- The input is converted to a list
- Empty inputs cannot reach the function
Answer: The result retains the input element type. T relates the element and return types for a call; it does not convert or validate values.
What does this program print? from typing import cast x = "7" y = cast(int, x) print(type(y).__name__, y is x)
- int False
- int True
- str False
- str True
Answer: str True. cast returns its argument unchanged. It does not parse numeric text.
A function accepts a Protocol with read() -> str. Which class satisfies that method contract statically?
- A class with read(self) -> str, without inheritance
- A subclass with read(self) -> int
- Any class with an attribute called read
- A class with only write(self, text: str)
Answer: A class with read(self) -> str, without inheritance. Structural typing needs a compatible signature, not an explicit protocol parent.
What does runtime_checkable establish for a protocol instance check?
- Every method returns the annotated type
- Every dictionary key has a validated value
- Required members are present, not that their type signatures match
- All generic type arguments match at runtime
Answer: Required members are present, not that their type signatures match. The runtime check is deliberately much shallower than static protocol checking.
What does this program print? from typing import NotRequired, TypedDict class Row(TypedDict): name: str note: NotRequired[str | None] a: Row = {"name": "A"} b: Row = {"name": "B", "note": None} print("note" in a, "note" in b) print(a.get("note") == b.get("note"))
- False False True
- False True False
- True True True
- False True True
Answer: False True True. Membership distinguishes omission from a present None; get without a distinct default does not.
A TypedDict field is annotated note: str | None, without NotRequired. What is its contract?
- The key is optional; its value must be str
- The key is required; its value may be None
- The key and value are both optional
- The constructor inserts the key as None
Answer: The key is required; its value may be None. Nullable values and optional keys express different things.
The browser prints the expected output for a typed program. What has that run verified?
- Static compatibility of every annotation
- Every possible caller’s argument types
- Runtime behavior for that execution
- The absence of errors on unexecuted branches
Answer: Runtime behavior for that execution. The browser does not run mypy. Run a checker separately to validate static claims.
Why does first(items: Sequence[T]) still check for an empty sequence?
- The element annotation does not establish that an item exists
- TypeVar forces sequences to be empty
- Sequence does not support indexing
- All generic checks happen at runtime
Answer: The element annotation does not establish that an item exists. The function needs an empty-input policy independently of its element type.
Continue this course
- Previous: Testing with unittest
- Next: Checkpoint: The Standard Library — Combine enums, namedtuples, functools and hashlib in a build — then a quiz
- Quick reference: Python cheat sheet