Python Type Hints Cheat Sheet

2022-01-13

Quick reference for Python 3.9+. For greater detail, see this cheat sheet.

Basic types:

1
2
3
4
5
x: int = 1
x: float = 1.0
x: bool = True
x: str = "python"
x: bytes = b"python"

Collection types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Basic collections (Python >=3.9)
x: list[int] = [1]
x: set[int] = {1}
x: tuple[str, int, bool] = ('python', 1, True)
x: dict[str, int] = { 'python': 1 }

# Other collections (Python >=3.9)
from collections import defaultdict, deque, Counter
x: defaultdict[str, int] = defaultdict(**{'python': 1})
x: deque[int] = deque([3])
x: Counter[str] = Counter({"python": 3})

Multiple or unknown types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from typing import Any, Optional, Union

# Any type
x: Any = ...

# int or None
x: Optional[int] = ...

# int or float
x: Union[int, float] = ...

Function types:

1
2
3
4
5
6
7
# Basic usage
def string_multiply(x: str, n: int) -> str:
    return x * n

# First-order functions
from typing import Callable
f: Callable[[str, int], str] = string_multiply

Generator and iterator types:

1
2
3
4
5
6
7
8
9
from typing import Iterator, Generator

# Generator[YieldType, SendType, ReturnType]
def some_numbers(n: int) -> Generator[int, None, None]:
    for i in range(n):
        yield i

g: Generator = some_numbers(100)
i: Iterator[str] = (x for x in 'python')