A hands-on project for learning Python's type system through exercises.
# Add development dependencies
uv add --dev pytest mypy
# Verify installation
uv run pytest --version
uv run mypy --versionEach exercise file contains:
- Docstrings explaining the concepts
- Stub functions/classes with
TODOcomments - Working implementations that need type hints
exercises/ex01_generics_basics.py
- TypeVar basics
- Generic functions
- Generic classes with
Generic[T]
exercises/ex02_typevar_constraints.py
- Constrained TypeVars (
TypeVar('T', int, str)) - Bounded TypeVars (
TypeVar('T', bound=SomeClass)) - Generic classes with bounds
exercises/ex03_protocols.py
- Basic Protocols
- Protocols with properties
@runtime_checkableProtocols- Generic Protocols
exercises/ex04_callable_and_overload.py
Callable[[Args], Return]type hints- Higher-order functions
@overloadfor multiple signaturesLiteraltypes with overloads
exercises/ex05_paramspec.py
ParamSpecfor preserving function signatures in decoratorsConcatenatefor adding/removing parameters- Decorator factories with full type safety
- Method decorators with
selfhandling
exercises/ex06_typeddict_and_guards.py
TypedDictfor typed dictionary structures (JSON, API responses)NotRequiredfor optional keys- Nested
TypedDictfor complex structures TypeGuardfor custom type narrowing functions- Discriminated unions with
Literaltype fields
exercises/ex07_classvar_final_self.py
ClassVarfor class variables vs instance variablesFinalfor immutable values and constants@finaldecorator to prevent subclassing/overridingSelftype for fluent interfaces and factory methods- Proper typing for method chaining and inheritance
exercises/ex08_newtypes_aliases_annotated.py
NewTypefor distinct types (UserId vs int)TypeAliasfor readable complex type definitionsAnnotatedfor attaching metadata to typescast()for type assertions when you know better- Building type-safe ID systems
- Read the exercise file and understand the concepts
- Add type hints to functions/classes marked with
TODO - Run tests to verify runtime behavior:
uv run pytest tests/test_ex01.py -v
- Run mypy to verify type correctness:
uv run mypy exercises/ex01_generics_basics.py
- Fix any type errors and repeat
- Start with Exercise 1 and progress in order
- Read the docstrings carefully - they explain what types are expected
- When stuck, check Python's
typingmodule docs - The tests show expected runtime behavior; mypy checks type safety