Learning Objectives: After this lesson, you'll understand Python's type annotation system, use generics and Protocol for flexible typing, leverage mypy for static analysis, and apply typing patterns for maintainable codebases.
Why Type Hints?
Type hints provide documentation, enable tooling, and catch bugs before runtime. Let's visualize how type checking works:
Type hints are optional annotations that tools use for analysis. Python itself ignores them at runtime!
The Problem with Dynamic Typing
Basic Type Annotations
Built-in Collection Types
Optional, Union, and None
Type Aliases and NewType
Generics: Flexible Type Parameters
Protocol: Structural Subtyping
Protocol enables "duck typing" with type checking. If it looks like a duck and quacks like a duck...
Complex Protocol Patterns
Callable Types
Literal and Final
TypedDict for Structured Dictionaries
Self Type and Type Guards
Overload for Multiple Signatures
Practice Exercises
Exercise 1: Generic Stack with Type Safety
Exercise 2: Protocol-Based Plugin System
Key Takeaways
| Concept | Description |
|---|---|
| Type Hints | Annotations for documentation and tooling |
| Generic | Type parameters for reusable code |
| Protocol | Structural subtyping (duck typing with types) |
| TypeVar | Placeholder for generic type parameters |
| Literal | Exact value types |
| TypedDict | Typed dictionary structure |
| overload | Multiple function signatures |
Type Checking Tools
| Tool | Purpose |
|---|---|
| mypy | Standard static type checker |
| pyright | Fast type checker (VS Code Pylance) |
| pytype | Google's type checker with inference |
Next Steps
In the next lesson, we'll explore Metaclasses and Class Customization—understand __new__ vs __init__, build metaclasses, and master __init_subclass__ for simpler class customization.
Ready to go deeper into Python's class system? Metaclasses await!