Modern Type Hinting in Python#
I’ve never been a really big fan of type hinting in Python, but there are some new features and conventions that makes it way more bearable imho. There are less imports needed, it looks cleaner and I might even start to like it if we all used this. Also, it gives me a good reason to update projects to the latest Python version.
Generic type hinting#
from typing import Dict, List
my_list: List = []
my_dict: Dict = {}
Since PEP 585 has been implemented in
Python 3.9
this can be replaced by the following:
my_list: list = []
my_dict: dict = {}
Union operator#
from typing import Union
my_int_or_str: Union[int, str]
Since PEP 604 has been implemented in
Python 3.10
this can be replaced by the following:
my_int_or_str: int | str
Union instead of Optional#
from typing import Optional
my_optional_str: Optional[str]
The makers of FastAPI recommend the following:
my optional_str: str | None
Final remarks#
It would be great if static lint/type checkers would recommend these practices.