Annotations in Python
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:
- Function Annotations
- Variable Annotations
Function Annotations are the more commanly used ones and are used as follows
: 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
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.
For further reference check https://www.python.org/dev/peps/pep-0483/