kuniga.me > Docs > Python Type Hints Cheatsheet
Python Type Hints Cheatsheet
Assumes Python 3.
Index
- Types
- Primitive Types
- Composite Types
- Callables
- Optional
- Any vs. object
- Union Types
- Type Alias
- Annotation Syntax
- Local Variables
- Turn off type checking
- Function Arguments with Default Value
- Classes
- Parametrized class
- Self
Types
Common types.
Primitive Types
Composite Types
List[int]
Dict[str, int]
Tuple[int, str]
Callables
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
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:
Type Alias
Annotation Syntax
How to provide annotation in different scenarios.
Local Variables
Turn off type checking
Function Arguments with Default Value
Classes
Parametrized class
Self
To use the class type within itself, we must include __future__.annotations
: