Working with Python
Type Hints
In Python 3.5, type hints were introduced as a means for adding type information. Starting with Python 3.9, many of these types are available as built-ins, so they no longer require importing from the typing
module. This page assumes you are using Python 3.9+.
Type hints can be thought of more as a documentation tool, or helper for IDEs and static analysis. Type hints are not enforced by the interpreter.
The biggest benefit of using type annotations is as a means to document code. They are particularly helpful with complex data structures, for example, making a list of tuples.
my_list_of_tuples: list[tuple[str, int]] = []
Basic Types
The core basic types: str
, int
, float
, and bool
.
my_string: str = ""
my_int: int = 0
my_float: float = 0.0
my_bool: bool = True
The core collection types: list
, dict
, tuple
, and set
.
my_list: list[str] = []
my_dict: dict[str, int] = {}
my_tuple: tuple[float, float] = ()
my_set: set[int] = set()
Functions
To use type hints in a function for arguments and return values.
def add(a: int, b: int) -> int:
return a + b
Use None
if your function does not return a value.
def hello(s: str) -> None:
print(f"Hello {s}")
Classes
To use type hints in a class.
class MyPoint:
x: int
y: int
def __init__(self, x: int, y: int):
self.x = x
self.y = y
Custom Types
You can create a custom type for your own classes.
class MyPoint:
x: int
y: int
def __init__(self, x: int, y: int):
self.x = x
self.y = y
Then you can use it as a type hint in other places:
my_point: MyPoint = MyPoint(1, 2)
Optional Types
Use Optional
for variables that can be None
.
from typing import Optional
my_optional_string: Optional[str] = None
Union Types
Use Union
for variables that can be of multiple types.
from typing import Union
my_union: Union[int, str] = "Hello"
my_union = 123
Type Aliases
Create type aliases for complex types.
from typing import List, Tuple
Coordinates = List[Tuple[float, float]]
my_coordinates: Coordinates = [(1.0, 2.0), (3.0, 4.0)]
Tools
Most editors these days have support for type hints to provide better autocomplete and error checking. The editors use tools like mypy
, Pyright
, or Pydantic
under the hood. For example, in Visual Studio Code, the Pylance extension uses Pyright.
To run mypy
on a file:
# install mypy
pip install mypy
# run mypy on a file
mypy my_file.py
To run mypy
on a directory:
mypy src/
As for what tool to use, I have no preference. I use mypy
for static analysis in a project and Pyright
for autocomplete in my editor.