10.2. Docstrings¶
Docstrings are multiline comments that appear either at the top of a mod- ule’s .py source code file or directly following a class or def statement. They provide documentation about the module, class, function, or method being defined. Automated documentation generator tools use these docstrings to generate external do cumentation files, such as help files or web pages. Docstrings must use triple-quoted, multiline comments rather than sin- gle-line comments that begin with a hash mark, # . Docstrings should always use three double quotes for its triple-quoted strings rather than three single quotes. For example, here is an excerpt from the sessions.py file in the popu- lar requests module:
# -- coding: utf-8 -- """ requests.session ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). """ import os import sys --snip— class Session(SessionRedirectMixin):
"""A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:
>>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]>--snip-- def get(self, url, **kwargs):
4 r"""Sends a GET request. Returns
Response
object. :param url: URL for the newRequest
object. :param **kwargs: Optional arguments thatrequest
takes. :rtype: requests.Response """
--snip--
The sessions.py file’s request contains docstrings for the module 2, the Session class 3, and the Session class’s get() method 4. Note that although the module’s docstring must be the first string to appear in the module, it should come after any magic comments, such as the shebang line or encod- ing definition 1.
Later, you can retrieve the docstring for a module, class, function, or method by checking the respective object’s doc attribute. For example, here we examine the docstrings to find out more about the sessions mod- ule, the Session class, and the get() method:
>>> from requests import sessions
>>> sessions.__doc__
'nrequests.sessionsn~~~~~~~~~~~~~~~~~nnThis module provides a Session object to manage and persist settings acrossnrequests (cookies, auth, proxies).n'
>>> sessions.Session.__doc__
"A Requests session.nn Provides cookie persistence, connection-pooling, and configuration.nn Basic Usage::nn >>> import requestsn >>> s = requests.Session()n >>> s.get('https://httpbin.org/get')n <Response [200]>nn Or as a context manager::nn >>> with requests.Session() as s:n ... s.get('https://httpbin.org/get')n <Response [200]>n "
>>> import requests\n
--snip--
>>> sessions.Session.get.__doc__
'Sends a GET request. ReturnsResponse
object.nn :param url: URL for the newRequest
object.n :param \*\*kwargs: Optional arguments thatrequest
takes.n :rtype: requests.Responsen '
Automated documentation tools can take advantage of docstrings to pro- vide context-appropriate information. One of these tools is Python’s built-in help() function, which displays the docstring of the object you pass it in a more readable format than the raw doc string directly. This is useful when you’re experimenting in the interactive shell, because you can immediately pull up information on any modules, classes, or functions you’re trying to use:
>>> from requests import sessions
>>> help(sessions)
Help on module requests.sessions in requests:
NAME
requests.sessions
DESCRIPTION
requests.session
~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings
-- More --
If the docstring is too large to fit onscreen, Python displays – More – at the bottom of the window. You can press ENTER to scroll to the next line, press the spacebar to scroll to the next page, or press Q to quit viewing the docstring.
Generally speaking, a docstring should contain a single line that summarizes the module, class, or function, followed by a blank line and more detailed information. For functions and methods, this can include information about their parameters, return value, and side effects. We write docstrings for other programmers rather than users of the software, so they should contain technical information, not tutorials.
Docstrings provide a second key benefit because they integrate docu- mentation into the source code. When you write documentation separate from code, you can often forget about it entirely. Instead, when you place docstrings at the top of the modules, classes, and functions, the informa- tion remains easy to review and update.
You might not always immediately be able to write docstrings if you’re still working on the code it’s meant to describe. In that case, include a TODO comment in the docstring as a reminder to fill in the rest of the details. For example, the following fictional reverseCatPolarity() function has a poor docstring that states the obvious:
def reverseCatPolarity(catId, catQuantumPhase, catVoltage): """Reverses the polarity of a cat. TODO Finish this docstring.""" --snip--
Because every class, function, and method should have a docstring, you might be tempted to write only the minimal amount of documentation and move on. Without a TODO comment, it’s easy to forget that this docstring will eventually need rewriting.
PEP 257 contains further documentation on docstrings at https://www .python.org/dev/peps/pep-0257/.