Many Erics working in a room

Docstrings

Docstrings

As your programs grow larger and your functions become more complex, it becomes increasingly important to document what your code does. Not just for other developers who might work with your code, but for your future self. You will be surprised how quickly you can forget what a function does when you come back to it weeks or months later.

A good rule of thumb is to write your code as if someone else is going to read it. Because eventually someone will. That someone might even be you.

What is a Docstring?

A docstring is a string placed at the very top of a function body, wrapped in triple quotes '''. It describes what the function does, what parameters it expects and what it returns. Unlike a regular comment, a docstring is not just ignored by Python. It is stored as part of the function and can be accessed programmatically.

Here is a function without a docstring:

And here is the same function with a docstring:

Now hover your cursor over the function call trigger() in VS Code and you will see the docstring appear as a tooltip:

Hovering over a function call shows the docstring tooltip in VS Code

This is one of the most practical advantages of docstrings. When you or another developer calls a function defined somewhere else in the program, you can see exactly what it does without hunting through the file to find the definition and read through the code.

If you look at any of Python's built in functions like len() or print() and hover over them in VS Code you will see the same thing. Every built in function has a docstring written by the Python development team. That is the description you see when you hover.

Accessing Docstrings

There are two ways to access a docstring programmatically. The first is using Python's built in help() function which prints a formatted description of the function including its docstring:

The second is using the dunder method .__doc__ which returns the raw docstring as a string that you can print directly:

Both give you access to the same information. help() formats it nicely and .__doc__ gives you the raw text.

When to Use Docstrings

Docstrings are particularly valuable in three situations:

Get into the habit of writing docstrings for every function you create. It takes thirty seconds and will save you hours in the long run.

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: Write Your First Docstring

Exercise 2: Document Your Own Functions

Exercise 3: Read a Built in Docstring

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course