Summary: In this tutorial, we will learn the significance of the -> (arrow annotation) in Python programming language.
The ->
in Python is one of the function annotations that was introduced in Python 3.0.
The official Python documentation explains that the Python 2.x series lacked the ability to annotate function parameters and return values, so to solve this, function annotations were officially introduced in Python 3.0.
The function annotations are nothing but metadata for Python functions. It does not play any role in the logic of the code but serves as documentation like docstrings.
The ->
(arrow) which is one of the function annotations is used to document the return value for a function.
>>> def add(a: int, b: int) -> int:
>>> return a+b
The ->
is written after the parameters list in the declaration of the function and marks the following expression as the return type/value.
For example, in the above code, we have mentioned int
after the arrow to signify that the corresponding function returns an integer value.
We can verify this by checking the __annotations__
attribute of the same function.
>>> add.__annotations__
{'a': <class 'int'>,
'b': <class 'int'>,
'return': <class 'int'>}
As we can see that the output dictionary has a key return
which has a value of class 'int'
.
Similarly, we can use any valid Python expression with the ->
annotation to document the return value for the function.
>>> def greet() -> 'Hello Programmers':
>>> return 'Hello Programmers'
>>>
>>> print(greet.__annotations__)
{'return': 'Hello Programmers'}
It is not mandatory to define arrow annotation for the functions in Python, as they are optional, but doing so makes the code more readable for other users and libraries.
Conclusion
The ->
(arrow) is used to annotate the return value for a function in Python 3.0 or later.
It does not affect the program but is intend to be consumed by other users or libraries as documentation for the function.
Nice bro. good one
Very helpful actually. Thanks for sharing your knowledge Adarsh!
Good job Adarsh, your explanation is clear…
Very clear the explanation. Thanks.
Thanks for sharing.
Nice Article. thanks for sharing.