Enhance your Python skills with function annotations for better code documentation and clarity!
Python’s function annotations provide a way to add additional metadata to function arguments and return types. These annotations serve as an informative tool for developers and IDEs but are ignored at runtime by the Python interpreter.
Function annotations are mainly used to provide descriptive metadata for arguments and return types, making your code more readable and maintainable. They are especially useful in large codebases, helping IDEs and static type checkers (like mypy) provide additional insights and error detection.
Here’s a simple example where we annotate the arguments with data types:
def myfunction(a: int, b: int):
c = a + b
return c
print(myfunction(10, 20))
print(myfunction("Hello ", "Python"))
Output:
30 Hello Python
You can also annotate the return type of a function using the arrow (->) syntax:
def myfunction(a: int, b: int) -> int: c = a + b return c print(myfunction(56, 88))
Output:
144
Function annotations can also be arbitrary expressions, not just data types. This allows flexibility and customization, such as describing the purpose of arguments:
def total(x : 'marks in Physics', y: 'marks in Chemistry'): return x + y print(total(86, 88))
Output:
174
You can specify default arguments along with annotations. Default arguments should come after the required ones:
def myfunction(a: "physics", b: "Maths" = 20) -> int: c = a + b return c print(myfunction(10))
Output:
30
You can annotate arbitrary positional (*args) and keyword (**kwargs) arguments as well:
def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int: pass print(myfunction.__annotations__)
Output:
{'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': }
Boost Your Python Skills 🚀
Master Python functions and annotations through our Python Certification Course and become an expert with hands-on projects!
