Sub topic 1
Type Hints and What a Type Checker Does
Prerequisites
You should know basic Python functions, classes, methods, and annotations such as list[int] and str | None. You should also know that tools such as mypy and pyright check annotations without running the program.
A type hint describes the values a function, variable, or class expects. A type checker reads these hints and reports likely mistakes before runtime. Python itself usually does not enforce them.
flowchart TD
A[Python source with annotations] --> B[Static type checker]
B --> C[Errors reported before running]
A --> D[Python interpreter]
D --> E[Program runs without type enforcement]Generic Functions: Relating Input and Output Types
A generic function uses one definition with several types. Its type parameter records a relationship between values. For example, first returns an item with the same type as the items it receives.
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
number = first([10, 20]) # inferred as int
word = first(("red", "blue")) # inferred as strHere, T is a type parameter. The checker infers T as int in the first call and str in the second. The function is still one runtime function.
The Classic Way: TypeVar and Generic
Python 3.12 introduced the bracket syntax used above. Older code commonly creates a TypeVar, which represents a type chosen by the checker, and uses Generic[T].
from typing import Generic, TypeVar
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(42) # checker infers Box[int]The TypeVar and Generic style remains valid. Use it when supporting older Python versions or matching an existing codebase.
Generic Classes
A generic class stores or processes values while preserving their type. The Python 3.12 form is shorter:
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
integers = Stack[int]()
integers.push(3)
value = integers.pop() # inferred as intThe checker rejects integers.push("three"), but Python does not add a runtime check for int.
Exercise
What does T connect in first[T](items: Sequence[T]) -> T?
Show answer
It connects the sequence element type to the function's return type.