Docstrings

Learn how to use docstrings in Python to document functions, classes, and modules effectively.

Loading...
Docstrings

In the previous lessons, we learned how to create functions using def, pass arguments, and return values.

But when you write a function, how will someone else know what it does, what arguments it expects, or what it returns?

That’s where docstrings come in.

What Are Docstrings?

A docstring is a string used to describe a module, function, class, or method.

It explains what a piece of code does and how to use it. Docstrings are usually placed right after the definition of the function, class, or module.

For example:

def square(n):
    """Return the square of a number."""
    return n ** 2

Here, the docstring is:

"""Return the square of a number."""

It tells us what the square() function does without needing to read the entire function.

Remember, we learned about comments. Comments help explain code to people reading it, while docstrings specifically document modules, functions, classes, and methods.

Accessing Docstrings

Python lets you access a function’s docstring using its __doc__ attribute.

Let’s use our previous example:

def square(n):
    """Return the square of a number."""
    return n ** 2
 
print(square.__doc__)
 
# Output:
# Return the square of a number.

The __doc__ attribute contains the function’s docstring.

You can also use Python’s built-in help() function to get information about a function.

help(square)
 
Output:
 
Help on function square in module __main__:
 
square(n)
    Return the square of a number.

The output may include additional details depending on the function you’re documenting.

Types of Docstrings

There are two common ways to write docstrings: single-line and multiline.

1. Single-Line Docstrings

For simple functions, a single line is often enough.

For example:

def greet(name):
    """Return a greeting message."""
    return f"Hello, {name}!"
 
def is_even(number):
    """Check if a number is even."""
    return number % 2 == 0

Each docstring briefly explains what its function does.

Notice that we’re using triple double quotes (""") even though the description fits on one line.

2. Multiline Docstrings

Sometimes, a function does more work and needs a longer explanation.

In that case, you can use a multiline docstring to describe its purpose, parameters, return value, and examples.

For example:

def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
 
    Args:
        length: The length of the rectangle.
        width: The width of the rectangle.
 
    Returns:
        The area of the rectangle.
    """
    return length * width

Here’s what each section means:

  • Summary: Explains what the function does.
  • Args: Describes the values passed to the function.
  • Returns: Explains what the function gives back.

We already learned about parameters and the return statement in earlier lessons. Docstrings help us describe them clearly.

The labels inside a docstring are plain text, so Python doesn’t automatically check whether your descriptions match the actual function.

Docstring Conventions

Python has guidelines for writing docstrings in a consistent way. These are described in PEP 257.

Here are a few useful conventions to follow:

  • Use triple double quotes: Write docstrings using """...""".
  • Start with a short summary: Explain the function’s purpose in one line.
  • Add a blank line in multiline docstrings: Separate the summary from the detailed explanation.
  • Describe what the function does: Keep the explanation clear and direct.

For example:

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

This is short, clear, and easy to understand.

For more complex functions, you can add details about arguments, return values, and possible errors.

You don’t need to memorize every convention right now. Start by writing a clear description of what each function does.

Try It Yourself

Now, a small exercise for you.

  • Write a function named cube() that returns the cube of a number. Add a docstring describing its purpose.
  • Create a function named greet() with a single-line docstring, then print its docstring using __doc__.
  • Write a function named calculate_area() with a multiline docstring describing its parameters and return value.
  • Use help() to display information about one of your functions.

👉 Next tutorial: Python Comments vs Docstrings