Documenting Python Functions with Docstrings

PythonBeginner
Practice Now

Introduction

In this lab, you will learn the importance of documenting your Python code using docstrings. We will explore how to access existing docstrings for built-in functions using the help() function and the __doc__ attribute.

Furthermore, you will gain practical experience in writing your own docstrings for custom functions and verifying their accessibility, making your code more understandable and maintainable for yourself and others.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Accessing Documentation with help()

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. It is used to document what the code does. Python's built-in help() function is an excellent tool for viewing this documentation in a clean, readable format. The help() function is designed for interactive use.

Let's start by viewing the documentation for the built-in print() function.

First, open a terminal in the WebIDE. You can do this by clicking the Terminal menu at the top of the screen and selecting New Terminal.

In the terminal, start the Python interactive shell by typing the following command and pressing Enter:

python

You will see the Python prompt (>>>). Now, use the help() function to get information about print():

help(print)

The terminal will display the documentation for the print function.

Help on built-in function print in module builtins:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    Prints the values to a stream, or to sys.stdout by default.

    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

(END)

This output explains what the function does, what parameters it accepts, and their default values. Press the q key to exit the help viewer and return to the Python prompt.

Now, exit the Python interactive shell by typing:

exit()

Accessing Raw Docstrings with __doc__

While help() is great for interactive use, you can also access the raw docstring of an object programmatically using its special __doc__ attribute. This attribute holds the docstring as a plain string.

Let's see this in action. In the WebIDE's file explorer on the left, find and open the file named access_docstring.py.

Add the following Python code to the file. This code will print the docstring of the built-in len() function.

## This script prints the docstring of the len() function.
print(len.__doc__)

Save the file (you can use the Ctrl+S shortcut).

Now, return to the terminal and run the script with the following command:

python access_docstring.py

The output will be the raw docstring for the len function.

Return the number of items in a container.

As you can see, __doc__ gives you the direct string content of the documentation, which can be useful for custom tools or scripts that process documentation.

Writing a Custom Function Docstring

Documenting your own functions is a fundamental practice for writing clean and maintainable code. A good docstring explains the function's purpose, its parameters, and what it returns.

Let's write a function and document it. Open the file my_function.py from the file explorer.

First, add the following function definition to the file:

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

Now, let's add a docstring. The docstring should be placed immediately after the def line and be indented at the same level as the function's code. We will use triple quotes ("""...""") for a multi-line docstring.

Modify my_function.py to include the docstring. We will also add a line to print the docstring to verify it works.

def greet(name, greeting="Hello"):
    """Greets a person with a given message.

    Args:
        name (str): The name of the person to greet.
        greeting (str, optional): The greeting message. Defaults to "Hello".
    """
    print(f"{greeting}, {name}!")

## Print the docstring of our greet function
print(greet.__doc__)

Save the file. Now, run the script from your terminal:

python my_function.py

You will see your custom docstring printed to the console.

Greets a person with a given message.

    Args:
        name (str): The name of the person to greet.
        greeting (str, optional): The greeting message. Defaults to "Hello".

This confirms that you have successfully documented your function and can access its docstring using the __doc__ attribute.

Using help() with Your Custom Function

In the previous step, we accessed our custom docstring using __doc__. Now, let's use the help() function to see a more polished and user-friendly view of our documentation, just like we did for the built-in print() function.

We will import our greet function into the Python interactive shell to use help().

In your terminal, start the Python shell again:

python

Once you see the >>> prompt, import the greet function from your my_function module (the filename my_function.py is treated as a module named my_function).

from my_function import greet

Now, use help() to view the documentation for your greet function:

help(greet)

You will see a nicely formatted output generated from your docstring.

Help on function greet in module my_function:

greet(name, greeting='Hello')
    Greets a person with a given message.

    Args:
        name (str): The name of the person to greet.
        greeting (str, optional): The greeting message. Defaults to "Hello".

(END)

Notice how help() automatically includes the function's signature (greet(name, greeting='Hello')) and formats the docstring for easy reading. This is why writing good docstrings is so valuable—it integrates directly with Python's built-in help system.

Press q to exit the help viewer, and then type exit() to leave the Python shell.

Summary

In this lab, you learned the fundamentals of documenting Python code with docstrings. You practiced accessing documentation for built-in functions using the interactive help() function and the __doc__ attribute. You then applied this knowledge by writing your own single-line and multi-line docstrings for a custom function, following standard conventions. Finally, you verified that your custom documentation is accessible through both __doc__ and Python's help() system, a key skill for creating readable, reusable, and maintainable code.