Function Annotations
Function Annotations
In Python function annotations helps us to attach metadata to function parameters and return values, add
IDEs and libraries could use annotations to indicate the function’s expected input and return types.
function annotations syntax
We use the following syntax to annotate function parameters and return value. By adding a color (:) after a parameter and an arrow (->) for return types
def function_name(parameter: annotation) -> return_annotation: pass
Annotating functions parameters
def add(a: int, b: int): return a + b
In this example:
The parameters a
and b
are annotated with int
, giving us hints that they should be integers
Annotating functions return value
def add(a: int, b: int) -> int: return a + b
In this example:
-
The parameters
a
andb
are annotated withint
, giving us hints that they should be integers -
The return type is annotated with int
Function annotations with default arguments
def add(a: int = 10, b: int = 20) -> int: return a + b