Annotations in Python

prerna prakash
2 min readJan 2, 2021

Annotations were introduced in Python 3.0 for type hinting. They are used to improve quality of scripts and are not enforced. They add metadata to functions and variables. They are completely optional and python on its own does not attach any meaning to them.

Annotations, in python, can be broadly classified in 2 types:

  1. Function Annotations
  2. Variable Annotations

Function Annotations are the more commanly used ones and are used as follows

Function Annotation
Output as dataframe
Print out annotations for function

: is used to specify type for parameters of a function, whereas -> is used to specify the type for its returned value.

Please note that annotations are only used for hinting and specify the DESIRED datatype but you can totally get away with sending a different datatype than the one specified in the function or variable as demonstrated in one of the examples below.

Variable annotations were introduced in python 3.6 (PEP 526)

These are simply used to hint the type of a variable

Variable Annotation ( b expects a str but is provided an integer)

Ensure that the annotations you provide are a vaild datatype, python will throw a Syntax Error if it isn’t. This is true for both variable annotation and also for function annotation.

When provided with an non existing datatype. In the above example ‘str’ would have worked just fine.

For further reference check https://www.python.org/dev/peps/pep-0483/

https://www.python.org/dev/peps/pep-0526/

--

--

prerna prakash

A lover of good stories | Data Engineer | Passionate Traveller | An obsessive reader