Python Function Annotations

Posted August 6, 2022 by  ‐ 1 min read

Python PEP-3107 introduced the syntax for adding metadata annotations. These annotations are evaluated at compile time and ignore at runtime. These annotations are used by many third party libraries like mypy for static type checks.

Function annotations can be of two types

String Based Annotations

We can pass any meaningful string to annotate the parameters and return type. It can be better explained with an example.

Example:

def calc_area(length: 'in mts', breadth: 'in mts') -> 'in sq.mts':
    return length * breadth

To get the annotations at run time

calc_area.__annotations__
# returns: {'length': 'in mts', 'breadth': 'in mts', 'return': 'in sq.mts'}

Type Based Annotations

It is also possible to pass types at the function definition. They are helpful in identifying type errors by many IDEs.

Example:

def calc_area(length: float, breadth: float) -> float:
    return length * breadth

To get the annotations at run time

calc_area.__annotations__
# returns: {'length': <class 'float'>, 'breadth': <class 'float'>, 'return': <class 'float'>}

Subscribe For More Content