1. Why Use Type Hints?
Python is a dynamically typed language, meaning variables can dynamically change types. While convenient, this can lead to unexpected runtime errors. Type Hints (introduced in Python 3.5) allow you to explicitly declare what data types variables, function arguments, and return values should be.- No Runtime Enforcement: Python does not raise errors at runtime if types mismatch.
- Improved Tooling: Type hints enable code editors (like VS Code) to provide autocompletion, inline documentation, and error highlighting.
- Static Analysis: Tools like
mypycan analyze your codebase to catch type bugs before you run the code.
2. Basic Type Annotations
To annotate a variable or parameter, add a colon: followed by the type name. To annotate a function’s return type, use ->.
3. Generic Collections
For collections like lists, dictionaries, tuples, and sets, Python 3.9+ allows you to use the built-in collection classes as types directly:4. Modern Union & Optional Syntax
Often, a variable or parameter might accept multiple types or be optional (nullable).Union Types (|)
Starting in Python 3.10, you can use the pipe operator | to represent a union of multiple types.
Optional Types (str | None)
To represent a value that could be a specific type or None, union that type with None:
[!NOTE] In older Python versions, you had to importUnionandOptionalfrom thetypingmodule:In modern Python development, the|syntax is the clean, industry-standard approach.