If you can’t find a good type for some value, you can use Any:
from typing import Anydef process_data(data: Any) -> None: # Can perform any operation on data print(data.anything()) # No type checking
The type Any is dynamically typed. Mypy doesn’t know anything about the possible runtime types of such values. Use it as an “escape hatch” only when necessary.
In Python 3.9 and later, built-in collection type objects support indexing:
Python 3.9+
Python 3.8 and earlier
# Built-in generic typesitems: list[str] # List of str objectscoordinates: tuple[int, int] # Tuple of two int objectsdata: dict[str, int] # Dictionary from str keys to int values# Variable lengthvalues: tuple[int, ...] # Tuple of arbitrary number of ints
from typing import List, Tuple, Dict# Legacy generic types from typing moduleitems: List[str] # List of str objectscoordinates: Tuple[int, int] # Tuple of two int objectsdata: Dict[str, int] # Dictionary from str keys to int values# Variable lengthvalues: Tuple[int, ...] # Tuple of arbitrary number of ints
Iterable, Sequence, and Mapping are generic types that correspond to Python protocols:
from collections.abc import Iterable, Sequence, Mappingdef process_items(items: Iterable[int]) -> None: for item in items: print(item)# Works with different typesprocess_items([1, 2, 3]) # listprocess_items((1, 2, 3)) # tupleprocess_items({1, 2, 3}) # set
A str object or a list[str] object is valid when Iterable[str] or Sequence[str] is expected.
In Python 3.9 and later, you can use built-in collection types directly with type parameters (e.g., list[int]). For Python 3.8 and earlier, import from the typing module instead: