Python Type Hinting
Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.
Basics
Type hints are defined using a colon : after the variable name and an arrow -> after the function parameters for the return type.
def greeting(name: str) -> str:
return 'Hello ' + name
Variable Annotation
age: int = 25
name: str = "Alice"
The typing Module
For more complex types, the typing module provides support. Note that in Python 3.9+, you can often use built-in collection types (like list and dict) directly instead of importing List and Dict.
from typing import List, Dict, Optional, Union
# List of integers
numbers: List[int] = [1, 2, 3]
# Dictionary with string keys and integer values
scores: Dict[str, int] = {"Alice": 10, "Bob": 20}
# Optional type (can be int or None)
user_id: Optional[int] = None
# Union type (can be int or float)
result: Union[int, float] = 10.5
Static Type Checking
Python is dynamically typed, so type hints are ignored at runtime. However, they are invaluable for static type checkers like mypy, IDEs, and linters to catch errors before running the code.