How to Use Typing Module in Python for Type Hints
Use the
typing module in Python to add type hints that specify expected data types for variables, function parameters, and return values. Import types like List, Dict, or Optional from typing and use them in your code to improve readability and help tools catch errors.Syntax
The typing module provides special types to specify expected data types in your code. You import the needed types and use them in function signatures or variable annotations.
List[int]: a list of integersDict[str, int]: a dictionary with string keys and integer valuesOptional[str]: a value that can be a string orNoneUnion[int, str]: a value that can be either an integer or a string
python
from typing import List, Dict, Optional, Union def greet(names: List[str]) -> None: for name in names: print(f"Hello, {name}!") age_map: Dict[str, int] = {'Alice': 30, 'Bob': 25} maybe_name: Optional[str] = None value: Union[int, str] = 42
Example
This example shows how to use the typing module to add type hints to a function that processes a list of numbers and returns their average as a float.
python
from typing import List def average(numbers: List[float]) -> float: total = sum(numbers) count = len(numbers) return total / count result = average([10.5, 20.0, 30.5]) print(f"Average: {result}")
Output
Average: 20.333333333333332
Common Pitfalls
Common mistakes when using the typing module include:
- Not importing the needed types from
typing. - Using built-in types like
listordictinstead ofListorDictin older Python versions (before 3.9). - Confusing
Optional[X]withUnion[X, None](they mean the same, butOptionalis clearer). - Forgetting that type hints do not enforce types at runtime—they are for readability and tools.
python
# Wrong: missing import # def process(items: List[int]) -> None: # pass # Right: from typing import List def process(items: List[int]) -> None: print(items)
Quick Reference
| Type Hint | Meaning |
|---|---|
| List[int] | List of integers |
| Dict[str, int] | Dictionary with string keys and integer values |
| Optional[str] | String or None |
| Union[int, str] | Integer or string |
| Tuple[int, str] | Fixed-size tuple with int and str |
| Any | Any type |
| Callable[[int, int], int] | Function taking two ints and returning int |
Key Takeaways
Import needed types from the typing module to add clear type hints.
Use type hints in function signatures and variable annotations for better code clarity.
Type hints help tools catch errors but do not enforce types at runtime.
Use Optional for values that can be None, and Union for multiple possible types.
Remember that Python 3.9+ supports built-in generic types like list[int] without typing.