4) Functions and Scope Lesson

What is a Python Docstring

10 min to complete · By Martin Breuss

To better document what your functions do, you should add docstrings to the function definition. In this lesson, you'll learn what docstrings are, how to write them, and how to use the information they provide.

Special Comments

Docstrings are special comments that describe functions, classes, and methods in Python.

Colorful illustration of a light bulb

Note: You'll learn about classes and methods in the next module of this course. For now, just keep in mind that docstrings apply to them in the same way as they do to functions.

What Are They For

The rationale for docstrings is to help you and others to know how to work with your functions. Docstrings should describe at least three aspects of your function:

  1. what it does
  2. what arguments it takes
  3. what it returns

Describing these important key points of a function makes it more accessible to other developers.

Writing a Docstring

Docstrings have a specific syntax that you need to follow, and additionally, there exist a couple of conventions on how to write good docstrings. The two essential aspects of a docstring are:

  1. Use triple-double quotes (""") to begin and end a docstring.
  2. Write it starting at the first line of your function body.

How exactly you format the content of your docstring and what you include is somewhat open for debate, but there are good guidelines that you should aim to follow.

To walk through creating a docstring for a function, you'll add one to the greet() function you've written earlier:

def greet(greeting, name):
    sentence = f"{greeting}, {name}! How are you?"
    return sentence

Following, for example, the style guide on Comments And Docstrings by Google, you could write a docstring for greet():

def greet(greeting, name):
    """Generates a greeting.

    Args:
        greeting (str): The greeting to use, e.g., "Hello"
        name (str): The name of the person you want to greet

    Returns:
        str: A personalized greeting message
    """
    sentence = f"{greeting}, {name}! How are you?"
    return sentence

Now you've turned greet() into a full-fledged example of a well-documented function with a descriptive name and an extensive docstring. What's the point?

Reading a Docstring

After writing your docstring, you're now able to quickly get information about how to use your function anytime you need it.

Open up a new interpreter session and copy greet(), including its docstring in there. You now have two options to read your docstring:

  1. help(): you can pass the function object as an argument to help()
  2. .__doc__: you can access the __doc__ attribute of greet

Try both of them and see what they show you. When calling help(greet), you should see a full-screen description show up in your terminal that displays the information from your docstring:

Help on function greet in module __main__:

greet(greeting, name)
    Generates a greeting.
    
    Args:
        greeting (str): The greeting to use, e.g., "Hello"
        name (str): The name of the person you want to greet
    
    Returns:
        str: A personalized greeting message

You can exit this screen by pressing the q character on your keyboard.

When you print the .__doc__ attribute of your function, you should see the same output, but right in your console:

print(greet.__doc__)

As you can see, having defined a descriptive docstring gives any developer who might use your function a good description of what it is about and how they can use it. This information is always accessible to them, given that they've defined or imported your function.

This also works for functions and classes from the standard library or with code that other developers wrote, as long as they've added docstrings!

Docstring Practise

  • Use help() to inspect the docstrings of built-in functions that you've already worked with.

Calling up these quick explanations can be extremely helpful; therefore, you should always aim to write docstrings for your code. However, typing a full-length docstring might sound like a lot of work, so here's a quicker way.

Install The VS Code Auto-Docstring Plugin

Like most repetitive tasks in programming, someone built an automation that makes life easier for you. VS Code has a plugin called Auto-Docstring that creates most of your docstrings for you. After typing """ in the first line of your function body, and pressing Enter, you'll get an auto-generated docstring where you just need to edit some parts of it:

def greet(greeting, name):
    """[summary]

    Args:
        greeting ([type]): [description]
        name ([type]): [description]

    Returns:
        [type]: [description]
    """
    sentence = f"{greeting}, {name}! How are you?"
    return sentence

You can jump between the different blanks you need to fill using your Tab character, which makes creating comprehensive docstrings much faster.

If you're not using VS Code, make sure to check the extensions of your favorite IDE; it'll most likely have a similar product that you can use. PyCharm, for example, includes this auto-completion for docstrings by default.

Colorful illustration of a light bulb

Additional Resources

Summary: What is a Python Docstring

  • Docstrings are special comments that you write right after starting a function definition. They start and end with triple-double quotes ("""), and there are various guidelines on how to write good docstrings.
  • The style you should use depends on what the organization you're working with uses as their standard; however, a good docstring should describe at least:
    1. what your function does
    2. what arguments it takes
    3. what it returns
  • You can follow Google's docstring guidelines and install an extension in your IDE that helps you to quickly auto-generate the basic structure of your docstrings.
  • Adding docstrings to your functions helps to keep your code well documented and allows developers to call up information about how to use your functions with help() or .__doc__.
  • Good documentation is helpful, and even though Python is a loosely-typed language where you don't need to define what type a variable has, there are options to add that information even more explicitly than just in your docstrings. In the next lesson, you'll learn about how to add type hints to your function definitions.