Explicitly define any type for x
x: Any
Type for list of integers
Python 3.9+
x: list[int]
Type for set of integers
Python 3.9+
x: set[int]
Type for dict where keys are string and values are float
Python 3.9+
x: dict[str, float]
Type for typles of integer, string, and float (like (3, "yes", 7.5))
Python 3.9+
x: tuple[int, str, float] = (3, "yes", 7.5)
Type for typles of integers of variadic size
Python 3.9+
x: tuple[int, ...]
Type for list where elements are either integers or strings
Python 3.10+
x: list[int | str] = [3, 5, "test", "fun"]
Type for variable which can be string or None
x: str | None
Optional[X] # 3.9 and earlier
Function with type annotations, taking two integer args and returning integer.
def plus(num1: int, num2: int) -> int:
return num1 + num2Type for x holding a function (or other object with \_\_call\_\_) taking two integers and returning float
x: Callable[[int, int], float] = f
Type for generator yielding integers
def gen(n: int) -> Iterator[int]:
Debug: print what type mypy infers for an expression
reveal_type(1)
Override the inferred type of an expression
b = cast(list[int], a)
Add additional annotation to a type (framework dependent)
Annotated[str, "this is just metadata"]