Type Annotation in Python

What is Type Annotation..?

Type Annotations or type hints in Python (or any other language) are used to indicate the data types of variables and inputs/outputs of functions and methods.

More clearly, These are expressions that are associated with variables or function/method arguments to make the code more readable for ourselves and the user, as these expressions do not have any meaning attached with them and these are ignored by the interpreter.

What is the syntax of Type Annotations..?

Type annotations have a straight-forward syntax i.e. variable_name : data_type.
For example:

name : str = 'Rohan'`
    age : int = 19

And for functions the syntax is:

def function_name(argument_1 : data_type,argument_2 : data_type) -> return_type:
        function body

For example:

def sum(num_1 : int,num_2 : int = 3) -> int:    # here 3 is the default value for the argument num_2
        return num_1 + num_2

How is this useful..?

First of all type annotations make the code more readable as even though these doesn't enforce the type on the variables and functions these are a quick way to validate the actual type of the vairables or arguments that are being passed to the functions cause a wrong type may lead to an error.

Type annotations are never gonna raise an error if the given variable or argument doesn't have the correct type cause these are just hinters and aren't enforced types.

Type annotations are used by code linters and if using an IDE will always highlight the arguments if these aren't of the correct type.

There are third party libraries like mypy which can be used for static type checking.

Annotations can also be accessed using function_name.__annotations__ i.e.:

def sum(num_1 : int,num_2 : int = 2) -> int:
        return num_1 + num_2

    sum.__annotations__    # accessing the __annotations__ attribute of the function


{'num_1': <class 'int'>, 'num_2': <class 'int'>, 'return': <class 'int'>}

Or taking a help on the function would yield a similar result too:

def sum(num_1 : int,num_2 : int = 2) -> int:
        A function that takes two integers as input and returns their sum
        return num_1 + num_2

Now, if we do help(sum) it will result in:

sum(num_1: int, num_2: int = 2) -> int
        A function that takes two integers as input and returns their sum

So, we could also say that type annotations are useful in documentation too.

For more information visit: