Python - Type Hints
Overview
Estimated time: 40–60 minutes
Add type hints to improve readability and catch errors earlier with static checkers like mypy or pyright. Learn basics, generics, and protocols.
Learning Objectives
- Annotate functions and variables with standard typing constructs.
- Define generic functions/classes with TypeVar and ParamSpec basics.
- Use Protocol for structural typing; run mypy/pyright checks.
Prerequisites
Basics
from typing import Optional
def greet(name: Optional[str]) -> str:
if name is None:
return "Hello"
return f"Hello, {name}"
Generics
from typing import TypeVar, List
T = TypeVar("T")
def first(xs: List[T]) -> T:
return xs[0]
Protocols
from typing import Protocol
class HasLen(Protocol):
def __len__(self) -> int: ...
def size(x: HasLen) -> int:
return len(x)
Run a checker
pip install mypy
mypy your_project/
Common Pitfalls
- Adding hints without running a checker—no feedback loop.
- Over-annotating trivial code; annotate public boundaries and tricky areas first.
Checks for Understanding
- When do you prefer Optional[T] or T | None?
- What’s structural typing and how does Protocol help?
Show answers
- Use T | None on Python 3.10+; Optional[T] is equivalent but more verbose.
- It checks whether a type matches a required shape; Protocol specifies that shape.
Exercises
- Add type hints to a small module and run mypy; fix reported issues.
- Create a Protocol for an object that has .read() -> str and write a function that uses it.