Function annotation in python3
Function annotations is newly introduced in python 3.X. According to official document, it’s completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information). Annotations are stored in the __annotations__
attribute of the function as a dictionary named as and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression.
It’s hard to understand literally, so let’s make it easier from coding.
def func(a, b, c):
return a + b + c
This is an easiest function, but if we inspect func(a, b, c) directly, we didn’t know what does a,b,c stand for: int?, str? or tuple? So, we can add annotation for function, like this.
def func(a:int, b:int, c:int):
return a + b +c
After annotating function, we can clearly understand parameters in function, and the same as return result using ->
symbol
def func(a:int, b:int, c:int) -> int:
return a + b +c
We know the result is int type now! I just do a simple way to illustrate function annotation, accutally, one can do anything in it as long as the annotation is useful to you.
def func(a:'1st num',b:'2nd num',c:'3rd num') -> 'output is sum of nums':
return a + b + c
or more complex
def func(a:int = 1 ,b:'2nd num' = 2 ,c:'3rd num' = 3) -> 'output is sum of nums':
return a + b + c