Show Menu
Cheatography

Python Type Hints Cheat Sheet (DRAFT) by

A series of Python datatypes.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Built-in Types

x = 1
Integer with no type
x: int = 1
Integer with explicit type
x: float = 1.0
Float
x: bool = True
Boolean
x: str = "­tes­t"
String
s: bytes = b"te­st"
Bytes

Explicit Collec­tions (from typing import ...)

x: List[int] = [1]
Explicitly typed list
x: Set[int] = { 2, 3 }
Explicitly typed set
x: Dict[str, float] = { "­str­": 1.0 }
Explicitly typed dict
x: Tuple = (1, "­yes­", 2.5)
Explicitly typed tuple
x: Tuple = (1, 2, 3)
Explicitly typed open tuple
x: list[int | str] = [1, 2, "­tes­t", "­tru­e"]
Union type (version 3.10+)
x: Option­al[str] = x | None or Union[X, None]
Optional type (union)
⬆️ "­tes­t" if condit­ion() else None
Optional type (condi­tional)
 

Collec­tions (from typing import ...)

x: list[int] = [1]
Array
x: set[int] = { 1, 2 }
Set
x: dict[str, float] = { "­tes­t", 1.0 }
Dictionary / Hash Table
x: tuple[int, str, float] { 1, "­yes­", 2.5 }
Tuple with 3 values
x: tuple[int, ...] = { 1, 2, 3 }
Tuple of variable size

Functions (from typing import...)

def functi­on(x: int) -> str
Basic function with a return value
def functi­on(x: int = 1) -> str
Basic function with a default value
def functi­on(x)
Basic function with no argument type
x: Callab­le[­[int, float], float]
Function as a class
def gen(n: int) -> Iterat­or[int]
Generator function that yields ints
def functi­on(­self, *args: str, **kwargs: str) -> int
All position args and keywords are strings