Annotations

PEP 3107 - Function Annotations

PEP 526 - Syntax for Variable Annotations

https://docs.python.org/3/howto/annotations.html
Annotations Best Practices

FUNCTION ANNOTATION

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: int) -> int:
   return a + b

sum_two_numbers.__annotations__
# {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

VARIABLE ANNOTATION


# When annotating a variable or a class attribute, assignment is optional:

class C:
    field: 'annotation'   # a class attribute annotation

# 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+

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.