Python Type Hints Cheatsheet > Docs > Python Type Hints Cheatsheet

Python Type Hints Cheatsheet

Assumes Python 3.


  1. Types
    1. Primitive Types
    2. Composite Types
    3. Callables
    4. Optional
    5. Any vs. object
    6. Union Types
    7. Type Alias
  2. Annotation Syntax
    1. Local Variables
    2. Turn off type checking
    3. Function Arguments with Default Value
    4. Classes
      1. Parametrized class
      2. Self


Common types.

Primitive Types

Composite Types


High-order functions. Callable[Tin, Tout]. Tin is a tuple with the types of input arguments. Tout is the return type. Example:


Optional[T] means None or T. Example:

Any vs. object

Any is equivalent to not providing the type annotation. object is the base of all types.

Union Types

When the variable can be one of many types:

from typing import TypeVar, Union
ID = Union[str, int]

Type Alias

MyNewType = Tuple[int, str]

Annotation Syntax

How to provide annotation in different scenarios.

Local Variables

s: str = 'abc'

Turn off type checking

pseudo_int: int = 'a'  # type: ignore

Function Arguments with Default Value

def inc(value: int, amount: int = 1) -> int:
    return value + amount


class C:

    _n: int

    def __init__(self, n: int) -> None:
        self._n = n

    def inc(self) -> None:
        self._n += 1

Parametrized class

T = 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:


We can’t use the class type until the class definition is over but we can use forward references (type in quotes):

class C:
    def create() -> 'C':
        return C()