A docstring describes a module, function, class, or method in plain English to help other coders understand the meaning better. You must define the docstring at the beginning of the module, function, class, or method definition. By doing so, the docstring becomes the __doc__
special attribute of that object. You can access the docstring of any Python object by calling its __doc__
attribute.
You can find a full tutorial on the docstring on my blog article: What is __ doc __ in Python?
Let’s have a short look at a minimal docstring example:
s = 'hello world' print(s.__doc__)
The output is the following multi-line docstring of the string function object:
''' str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'. '''
But how can you define the docstring in a single line of Python code?
The docstring can be either defined in multiple lines using the triple quotes or in a single line.
One-Line Docstring
Per convention, you use one-line docstrings if the function, module, class, or method is obvious enough to warrant a short explanation—but nothing more. You can enclose the one-liner docstring within single quotes, double quotes, or even triple quotes. However, enclosing the one-liner docstring in a triple quote is the most Pythonic way.
For example, the following function can be easily understood. Therefore, a one-liner docstring is sufficient to describe its behavior:
def add(x, y): '''Add both arguments and returns their sum.''' return x + y print(add.__doc__) # Add both arguments and returns their sum.
There are some conventions to consider when writing one-liner docstrings:
- Use triple quotes for the one-liner docstring—even if this is not strictly needed. It improves consistency and simplifies later extensions of the docstring.
- Place the closing quotes on the same line as the opening quotes for clarity. Otherwise it wouldn’t be a one-liner docstring in the first place.
- Don’t use a blank line before or after the docstring. Just start coding right away!
- If possible, formulate the docstring as a phrase ending in a period. Why? Because this encourages you to write prescriptive docstrings such as “Do X” or “Return Y” rather than descriptive “Returns X” or “Does Y”.
- Don’t use the docstring as a “signature” reiterating the information already given in the function/method definition.
So far so good. But if this is a one-liner docstring—how does a multi-line docstring look like?
Multi-Line Docstring
A multi-line docstring consists of multiple lines of Python code:
def add(a=0, b=2): """Add two integers. Keyword arguments: a -- the first argument (default 0) b -- the second argument (default 2) """ if a == 0: return b else: return a + b
In this case, the multi-line docstring is more complicated. It first starts with a general description of the function, followed by a list-like explanation of all the arguments. This is a clean and readable way to write docstrings!
Try It Yourself: Have a look at the following interactive code shell:
Exercise: Print the docstring to the Python shell and run it in your browser!
Best Practices
There are a couple of best-practices called Docstring Conventions as defined in the official PEP standard. Adhere to them when defining your docstrings. Here are the 7 most important docstring conventions:
- All modules, function, methods, and classes should have docstrings.
- Always use
"""triple double quotes"""
around your docstrings for consistency reasons. - Use triple quotes even if the docstring fits into a single line. This allows for easy expansion later.
- No blank line before or after the docstring—except for classes where you should add one line after the docstring.
- Use a phrase that describes what your code is doing such as
"""Do X and return Y."""
ending in a period. Don’t use a description such as"""Does X and returns Y."""
. - Multi-line docstrings start with a summary line (like the one-liner docstring), followed by a blank line, followed by a closer description such as
argument --- name of the person (string)
to describe one of the arguments of the function or method. For example, you can use one line per argument. - Start a multi-line docstring immediately in the same line of the opening
"""triple double strings...
rather than starting the text in a new line.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.