Variable Type Annotations
You can specify the expected data type of a variable by appending a colon and the type identifier immediately after the variable name.
username: str = ""
user_age: int = 0
credit_score: float = 0.0
preferences: dict = {}
permissions: list = []
coordinates: tuple = ()
Function Parameter and Return Annotations
For functions, parameter types follow the same colon syntax, while the expected return type is indicated using an arrow (->) placed before the function body.
def format_record(uid: str, entries: int, active: bool = True) -> dict:
...
The typing Module
Introduced in Python 3.5 as a built-in standard library, the typing module expends upon basic type hinting by offering robust and complex type definition utilities.
Core typing Constructs
from typing import List, Tuple, Dict, Union, Optional, Callable, Iterable, Type
emails: List[str] = [] # A list containing only strings
record: Tuple[int, str] = () # A 2-element tuple: integer followed by string
mapping: Dict[str, float] = {} # A dictionary with string keys and float values
payload: Union[str, bytes, None] = None # Accepts string, bytes, or None
nickname: Optional[str] = None # Shorthand for Union[str, None]
transformer: Callable[[str], int] # A callable taking a string and returning an int
digits: Iterable[int] # An iterable object yielding integers
klass: Type[BaseModel] # The class BaseModel or its subclass itself
These parameterized types enclosed in square brackets can be nested and combined freely to construct precise type definitions.
Custom Class Ennotations
User-defined classes naturally funcsion as valid types for annotations. This practice is particularly crucial for maintaining IDE autocomplete functionality and preventing errors when dealing with dynamically instantiated objects or deeply nested data structures.
from typing import List
class UserProfile:
pass
profile: UserProfile = UserProfile() # An instance of UserProfile
user_directory: List[UserProfile] = [] # A list composed of UserProfile instances