Python Type Hints Cheatsheet

kuniga.me > Docs > Python Type Hints Cheatsheet

Python Type Hints Cheatsheet

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.

Annotation Syntax

How to provide annotation in different scenarios.

Local Variables

s: str = 'abc'

Turn off type checking

pseudo_int: int = 'a'  # type: ignore

Classes

class C:

    _n: int

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

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