Python Type Hints Cheatsheet

kuniga.me > Docs > Python Type Hints Cheatsheet

Python Type Hints Cheatsheet

Assumes Python 3.

Index

  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

Types

Common types.

Primitive Types

Composite Types

Callables

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

Optional

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

Classes

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:
        self.items.append(item)

Self

To use the class type within itself, we must include __future__.annotations:

from __future__ import annotations
class C:
    @staticmethod
    def create() -> C:
        return C()