PEP 3107 - Function Annotations
PEP 482 - Literature Overview for Type Hints
PEP 484 - Type Hints
PEP 526 - Syntax for Variable Annotations
PEP 563 - Postponed Evaluation of Annotations
PEP 649 - Deferred Evaluation Of Annotations Using Descriptors
https://docs.python.org/3/howto/annotations.html
Annotations Best Practices.
https://docs.python.org/3/library/typing.html
'typing' - Support for type hints [Py3.5+].
https://typing.readthedocs.io/en/latest/spec/index.html
Specification for the Python type system.
Python supports annotations on three different types: functions, classes, and modules.
Function arguments may have an annotation of the form ': expression' following the parameter name. Any parameter may have an annotation, even those of the form *identifier or **identifier. Functions may have 'return' annotation of the form '-> expression' after the parameter list.
The annotation values are available as values of a dictionary keyed by the parameters’ names in the __annotations__ attribute of the function object.
# Syntax. def function_name(arg1: expression, arg2: expression = value) -> expression: statements def function_name(*arguments: expression, **keywords: expression)-> expression: statements
# Function annotations are usually used for type hints. def sum_two_numbers(a: int, b: float) -> complex: return complex(a + b) sum_two_numbers.__annotations__ # {'a': <class 'int'>, 'b': <class 'float'>, 'return': <class 'complex'>}
# When annotating a variable or a class attribute, assignment is optional: class C: field: int # a class attribute annotation def __init__(self) -> None: pass C.__annotations__ # {'field': <class 'int'>}
# Variable annotations are usually used for type hints. import typing count: int = 0 # a variable annotation some_list: typing.List[int] = [1, 3] # from 'typing' module some_list: list[int] = [1, 3] # Py3.9+ some_dict: typing.Dict[str, float] = {"a": 1.2} # from 'typing' module some_dict: dict[str, float] = {"a": 1.2} # Py3.9+ coords: typing.Tuple[float, float] = (1.2, 3.4) # from 'typing' module coords: tuple[float, float] = (1.2, 3.4) # Py3.9+ Url = str # type alias
Type hints are optional and are not enforced by Python but they are useful to static type analysis tools, and aid IDEs with code completion and refactoring.