visit
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.
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 to them and are ignored by the interpreter.
Type annotations have a straight-forward syntax i.e. variable_name : data_type
. For example:
name : str = 'Rohan'`
age : int = 19
def function_name(argument_1 : data_type,argument_2 : data_type) -> return_type:
function body
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
First of all type annotations make the code more readable, as, even though these don't enforce the type on the variables and functions these are a quick way to validate the actual type of the variables or arguments that are being passed to the functions that 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'>}
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.
We learned about type annotations or now that we know what these are it would be better to call these types of hints. Alongside all other benefits, these can also come in handy when debugging functions working based on the input arguments passed to it. Moreover, the fact that these are also used for documentation purposes it is a good habit to use these as it will not only be good for us to read through or get a help documentation
but also for others to all those who are gonna use our code in the future.