kuniga.me > Docs > Python Type Hints Cheatsheet
Assumes Python 3.
Common types.
boolintstrfloatList[int]Dict[str, int]Tuple[int, str]High-order functions. Callable[Tin, Tout]. Tin is a tuple with the types of input arguments. Tout is the return type. Example:
Callable[[str, str], str]Optional[T] means None or T. Example:
Optional[int]Any is equivalent to not providing the type annotation. object is the base of all types.
When the variable can be one of many types:
from typing import TypeVar, Union
ID = Union[str, int]MyNewType = Tuple[int, str]Keywords: dict, record, json.
class Person(TypedDict):
name: str
age: int
p: Person = {
"name": "Joe",
"age": 32,
}How to provide annotation in different scenarios.
s: str = 'abc'pseudo_int: int = 'a' # type: ignoredef inc(value: int, amount: int = 1) -> int:
return value + amountclass C:
_n: int
def __init__(self, n: int) -> None:
self._n = n
def inc(self) -> None:
self._n += 1T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
# Create an empty list with items of type T
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)To use the class type within itself, we must include __future__.annotations:
from __future__ import annotations
class C:
@staticmethod
def create() -> C:
return C()