Skip to main content
Type hints tell Python (and other developers) what type of data a variable should hold:
The : 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:
No error. Python runs this code without complaint. So why use them?

Benefits of type hints

Type hints give you three benefits:
  1. Documentation - Code becomes self-explanatory
  2. IDE support - Autocomplete, error detection, refactoring
  3. Validation tools - Pydantic, mypy, and others use them
Without type hints:
With type hints:

Basic types

The four types you’ll use constantly:

Container types

For collections of data, you specify what’s inside:
Since Python 3.9+, use lowercase built-in types (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. Use Optional or the | syntax:
Use Optional when a value might be None:

Literal types

When a value must be one of specific options:
Real-world example:

Function type hints

Type hints work on function parameters and return values:
The -> 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:
Type hints are just hints. They don’t enforce anything. This is where Pydantic comes in. Pydantic reads your type hints and actually validates data against them.

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.