Docstrings and annotations

Docstrings and annotations

In Python, a docstring is a string literal that appears as the first statement in a module, function, class, or method definition. It is used to provide documentation for the code and can be accessed using the __doc__ attribute of the object.

Docstrings are enclosed in triple quotes (“””), and can span multiple lines. They can be used to describe what a function does, what arguments it takes, what it returns, and any other relevant information.

For example, consider the following function definition with a docstring:

python

def add(x, y): “”” Returns the sum of two numbers. Parameters: x (int): The first number. y (int): The second number. Returns: int: The sum of x and y. “”” return x + y

In this function, the docstring provides information about the function’s purpose, the parameters it takes, and the return value.

In addition to docstrings, Python also supports function annotations. Annotations are a way to attach metadata to function arguments and return values. They can be used to provide additional information about the types and behavior of function parameters and return values.

For example, consider the following function definition with annotations:

php

def add(x: int, y: int) -> int: return x + y In this function, the annotations int indicate that the arguments x and y are expected to be integers, and the -> int annotation indicates that the function returns an integer. Annotations can be useful for type checking and code analysis, and are typically used in combination with a static type checker like mypy.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
The return statement
Byte compiled pyc files

Get industry recognized certification – Contact us

keyboard_arrow_up