: str, : int, : float, and : bool are type hints.
Python doesn’t enforce them
Here’s the key thing: Python ignores type hints at runtime. They’re just documentation:Benefits of type hints
Type hints give you three benefits:- Documentation - Code becomes self-explanatory
- IDE support - Autocomplete, error detection, refactoring
- Validation tools - Pydantic, mypy, and others use them
Basic types
The four types you’ll use constantly:Container types
For collections of data, you specify what’s inside:list, dict, set, tuple). Older code uses uppercase imports from typing (List, Dict). These are equivalent but lowercase is now preferred.
Optional values
Sometimes a value might not exist. UseOptional or the | syntax:
Optional when a value might be None:
Literal types
When a value must be one of specific options:Function type hints
Type hints work on function parameters and return values:-> str after the parentheses indicates the return type.
Common type hint patterns
Here are patterns you’ll see constantly in Python code:Type hints don’t validate
Remember: Python ignores type hints. This code runs without error:Learn more
Practice & Exercises
To reinforce what you’ve learned, practice with these interactive notebooks:Follow-Along Practice
Practice declaring basic variable type hints, annotating function parameters/returns, and working with modern union and optional types.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises annotating function signatures and handling optional/union input parameters.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
Now that you understand type hints, let’s use them with Pydantic to create your first validated data model.Your First Model
Learn how to create validated data structures with BaseModel.