Type Hints & mypy Static Typing
Add gradual typing with Python 3.13 type hints โ Union, Optional, TypeVar, Generic, Protocol, TypedDict, and mypy strict mode.
Part 1: What You Will Learn
- Annotate variables, functions, collections, and optional values.
- Use generics with
TypeVar. - Describe structural interfaces with
Protocol. - Define dictionary shapes with
TypedDictand runmypy.
Part 2: Key Concepts
Type hints do not normally change Python runtime behaviour. They give editors and static type checkers more information so mistakes can be detected before execution. Modern Python uses built-in generic syntax such as list[str] and union syntax such as str | None.
Part 3: Topic-Specific Code Examples
from typing import Protocol, TypeVar, TypedDict
class StudentRow(TypedDict):
student_id: str
name: str
mark: int
class HasLabel(Protocol):
def label(self) -> str: ...
T = TypeVar("T")
def first_or_none(items: list[T]) -> T | None:
return items[0] if items else None
class Student:
def __init__(self, student_id: str, name: str) -> None:
self.student_id = student_id
self.name = name
def label(self) -> str:
return f"{self.student_id} - {self.name}"
def print_label(item: HasLabel) -> None:
print(item.label())
rows: list[StudentRow] = [
{"student_id": "S001", "name": "Aisha", "mark": 88},
{"student_id": "S002", "name": "Ben", "mark": 74},
]
student = Student("S003", "Chong")
print_label(student)
print(first_or_none(rows))python -m pip install mypy mypy --strict student_types.py
Part 4: How the Example Works
TypeVar lets first_or_none() preserve the element type of any list. Protocol means a class does not have to inherit from HasLabel; it only needs a compatible label() method. TypedDict gives dictionary keys and values a known static shape.
Part 5: Hands-On Practice
Mini project โ Typed Inventory. Create a generic Repository[T] with add() and get_all(). Define a ProductRow TypedDict and run mypy --strict until the project reports no type errors.
Part 6: Next Steps
Run and modify the examples in Visual Studio 2026, then continue to Lesson 16. Return to Python Tutorial Home to review the complete curriculum.