0
0
Pythonprogramming~5 mins

Docstrings and documentation in Python

Choose your learning style9 modes available
Introduction

Docstrings help explain what your code does in simple words. They make your code easier to understand for others and for yourself later.

When you write a function and want to explain what it does.
When you create a class and want to describe its purpose.
When you want to add instructions or notes inside your code.
When you share your code with others so they can understand it quickly.
When you want to generate automatic documentation from your code.
Syntax
Python
"""
Short description.

More details if needed.
"""
Docstrings are written inside triple quotes (""" or '''), usually right after a function, class, or module definition.
They can be one line or multiple lines long.
Examples
A simple one-line docstring for a function.
Python
def greet():
    """Say hello to the user."""
    print("Hello!")
A multi-line docstring explaining parameters and return value.
Python
def add(a, b):
    """
    Add two numbers and return the result.

    Parameters:
    a (int): First number
    b (int): Second number

    Returns:
    int: Sum of a and b
    """
    return a + b
Docstrings for a class and its method.
Python
class Car:
    """A class to represent a car."""

    def __init__(self, make, model):
        """Initialize make and model of the car."""
        self.make = make
        self.model = model
Sample Program

This program defines a function with a docstring. It prints the result of multiplication and then prints the docstring itself.

Python
def multiply(x, y):
    """Multiply two numbers and return the product.

    Args:
        x (int or float): First number
        y (int or float): Second number

    Returns:
        int or float: Product of x and y
    """
    return x * y

print(multiply(4, 5))
print(multiply.__doc__)
OutputSuccess
Important Notes

Docstrings are accessible at runtime via the .__doc__ attribute.

Good docstrings improve code readability and help tools create documentation automatically.

Keep docstrings clear and concise, focusing on what the code does, not how.

Summary

Docstrings explain your code in simple words inside triple quotes.

Use them right after functions, classes, or modules to describe their purpose.

They help others and yourself understand and use your code better.