In this article, you will understand what are docstrings in Python, its importance, how to write docstrings and different types of docstrings.


The code you write today will be read by you or by your team after a few days or months or maybe after few years. If the code is not readable then you are going to spend your precious time figuring out what the module, class, function, or method is doing. Python docstrings are a great tool to make your code readable. Once docstrings are added to the code, you can easily access docstrings using help() and doc attribute on the object and understand what the module, class, function, or method is doing.

This quote from Guido conveys the importance of commenting and documenting your code.

“Code is more often read than written.” Guido van Rossum Tweet

Here is another one from Damian Conway on documentation.

“Documentation is a love letter that you write to your future self” Damian Conway Tweet

So how do you write readable code? There are a number of guidelines on writing readable code. However, in this article, we’ll focus on one of the methods called docstrings. Along the way, you will learn how docstrings are used with examples.

What are Docstrings

Docstrings or documentation strings are the string literals that appear in the first line of module, class, function, or methods definition. The docstrings are created by enclosing the documentation text within '''triple single-quotes''' or """triple double-quotes""". Docstrings should explain what the module, class, function, or method does not how it does.

There are two types of docstrings: one-line docstrings and multi-line docstrings. Let’s understand both types with examples.


Python Docstrings and Its Importance
2.15 GEEK