From point A to point B
Point A: you write functions that work, but 3 months from now neither you nor your team will remember what each parameter expected. Point B: by the end of this chapter, you'll document your code with docstrings, read them with help() and pydoc, and generate a documentation site with Sphinx.
Documentation isn't decoration. In network automation, someone else will run your script against real devices; the documentation tells them what it can break.
- Docstrings: documentation that lives inside the object
- PEP 257 conventions
help()andpydocin the terminal and the browser- Basic reStructuredText markup
- Fields for parameters, return values and exceptions
- Generating documentation with Sphinx
- Google and NumPy styles with napoleon
- Type annotations as documentation
Docstrings: documentation inside the object
You saw in earlier chapters that functions, classes and modules have a special attribute: __doc__. It stores that object's documentation string, or docstring.
You could assign it some text by hand, like any attribute. But Python offers a shortcut: if the first statement of a function, class or module is a string literal, that string is automatically stored in __doc__.
def describe_interface(name):
"""Returns a short description of the interface."""
return f"Interface {name}"
print(describe_interface.__doc__)
describe_interface.__doc__ = "Describes a network interface by its name."
print(describe_interface.__doc__)
Returns a short description of the interface.
Describes a network interface by its name.
The difference from a # comment matters. The comment disappears at compile time; the docstring stays in the object. That's why you can read it while the program runs.
print as a statement (print haz_algo.__doc__). In Python 3, print() is a function. Also, since 3.13, the compiler strips the common indentation from docstrings, so .pyc files take up less space. And if you run with python -OO, docstrings are removed and __doc__ is None: don't rely on them for program logic.PEP 257 conventions
PEP 257 is the document that sets how docstrings are written in the Python community. It isn't an interpreter rule but an agreement. Following it means tools and people understand your documentation without surprises.
- Always use triple double quotes:
"""…""". - The first line is a short summary that ends with a period. It describes what the code does, not how.
- If you need more detail, leave a blank line after the summary and continue.
- Document modules, public classes, functions and public methods.
- A class's docstring describes the class; the
__init__docstring describes how to create the instance.
"""Tools for working with the router inventory.
This module groups small functions to validate and describe
network devices before you configure them.
"""
class Router:
"""Represents a router in the inventory."""
def __init__(self, hostname: str, mgmt_ip: str) -> None:
"""Creates a router with its name and its management IP."""
self.hostname = hostname
self.mgmt_ip = mgmt_ip
The first line of a module's docstring is its synopsis. Several tools use it as a short description, so it's worth writing it well.
help() and pydoc
The help() function shows the documentation of any object. Under the hood, it uses the pydoc module, which is part of the standard library. pydoc walks through the object, reads its docstring and those of its members, and presents them formatted.
>>> import inventory
>>> help(inventory.prefix_to_mask)
Help on function prefix_to_mask in module inventory:
prefix_to_mask(prefix: int) -> str
Converts a prefix length into a dotted-decimal mask.
…
Notice that help() also shows the signature with its type annotations. Later on, you'll see why that already counts as documentation.
pydoc also works as a command-line tool, similar to Javadoc in Java. You run it with python -m pydoc:
$ python -m pydoc ipaddress # documentation in the terminal
$ python -m pydoc ./inventory.py # a specific file (needs a /)
$ python -m pydoc keywords # lists the keywords
$ python -m pydoc topics # lists the help topics
$ python -m pydoc modules # lists the installed modules
$ python -m pydoc -k IPv4 # searches the synopses
ipaddress - A fast, lightweight IPv4/IPv6 manipulation library in Python.
$ python -m pydoc -w ./inventory.py # generates inventory.html
wrote inventory.html
The -k option searches for a word only in the first line of each module. That's another reason to take care of the synopsis.
To browse the documentation in your browser, pydoc includes a small web server:
$ python -m pydoc -b # opens the browser on a free port
$ python -m pydoc -p 8765 # serves on http://localhost:8765/
Server ready at http://localhost:8765/
Server commands: [b]rowser, [q]uit
server> q
Server stopped
pydoc.py as a script and mentioned the -g option, which opened a graphical interface. That interface was removed in Python 3.3: its replacement is -b, which uses your browser. Today, the recommended way is python -m pydoc, which guarantees you use your interpreter's pydoc. The -n option sets the server's host name.Basic reStructuredText markup
pydoc shows the text as is. It doesn't know that a line describes a parameter or that a word should be in italics. For that, you need a markup language and a tool that understands it.
reStructuredText (reST) is that language in the Python world. David Goodger created it as part of the Docutils project. It's used to write the PEPs and Python's official documentation.
Network inventory
=================
Edge devices
------------
Text in *italics*, in **bold** and as ``code``.
You escape the asterisk like this: \* isn't italics.
* router
* switch
* firewall
#. Configure the VLAN.
#. Assign the interface.
#. Verify with ``show vlan``.
- Italics: one asterisk on each side. Bold: two.
- Inline code: two backticks on each side.
- Escaping: the backslash cancels the special meaning.
- Titles: you underline them (or put a line above and below) with characters such as
=or-. Each new combination creates a lower level. - Lists: with
*,-or+. Numbered lists use1.or#.to number automatically.
Fields for parameters, return values and exceptions
reST lets you add fields (field lists): lines that start with :name:, optionally with an argument, followed by text. Sphinx interprets these fields and turns them into sections such as "Parameters" or "Returns".
def prefix_to_mask(prefix: int) -> str:
"""Converts a prefix length into a dotted-decimal mask.
Computes the mask's 32 bits and splits them into 4 octets.
:param prefix: Prefix length, from 0 to 32.
:type prefix: int
:return: The mask in dotted-decimal notation.
:rtype: str
:raises ValueError: If the prefix is outside the 0-32 range.
.. note:: Only supports IPv4.
"""
if not 0 <= prefix <= 32:
raise ValueError(f"prefix out of range: {prefix}")
bits = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
return ".".join(str((bits >> d) & 0xFF) for d in (24, 16, 8, 0))
print(prefix_to_mask(24)) # → 255.255.255.0
print(prefix_to_mask(30)) # → 255.255.255.252
The book taught these fields with Epydoc. Most of them live on in Sphinx under the same name; others became directives (blocks that start with ..). This table maps what the book proposed to what you use today.
| In the book (Epydoc) | Today with Sphinx | What it's for |
|---|---|---|
:param p: | :param p: | Describes the parameter p. |
:type p: | :type p: or the annotation p: int | The parameter's expected type. |
:return: | :return: or :returns: | What it returns. |
:rtype: | :rtype: or the annotation -> str | Type of the return value. |
:keyword p: | :keyword p: | An argument passed by name. |
:raise e: | :raises e: | When the exception e is raised. |
:ivar v: / :cvar v: | :ivar v: / :cvar v: | Instance / class attribute. |
:type v: (variable) | :vartype v: | An attribute's type. |
:var v: (module) | A #: comment above the variable | Documents a module variable. |
:note:, :attention:, :warning: | .. note::, .. attention::, .. warning:: | Highlighted notices. |
:bug: | .. warning:: and your issue tracker | A known bug. |
:see: | .. seealso:: | Related information. |
:todo: | .. todo:: (sphinx.ext.todo extension) | A pending change. |
:version:, :change: | .. versionadded::, .. versionchanged:: | The object's history. |
:status: | .. deprecated:: | Marks something as deprecated. |
:author:, :organization:, :license:, :contact: | author in conf.py and the authors and license fields in pyproject.toml | The project's authorship and license. |
The book also showed list-style fields, such as :Parameters:, to describe all the parameters at once. Today, the Google and NumPy styles play that role, and you'll see them in a moment.
__docformat__ = "restructuredtext" variable that Epydoc required: Sphinx assumes reST.Generating documentation with Sphinx
Sphinx is a third-party package. Install it inside a virtual environment (you'll see this in detail in chapter 21):
$ python -m pip install sphinx
A Sphinx project needs at least 2 files: conf.py with the configuration and index.rst with the content. The sphinx-quickstart command creates them for you with guided questions. Here, you write them by hand to understand each line.
# docs/conf.py
import sys
from pathlib import Path
# Lets Sphinx import your modules from the parent folder
sys.path.insert(0, str(Path(__file__).parent.parent))
project = "Network inventory"
author = "Network team"
extensions = [
"sphinx.ext.autodoc", # extracts the docstrings from the code
"sphinx.ext.napoleon", # understands the Google and NumPy styles
]
language = "en"
Network inventory
=================
Documentation generated from the *docstrings*.
.. automodule:: inventory
:members:
The automodule directive imports the module and documents all its public members. Then you build the HTML site:
$ sphinx-build -b html docs docs/_build/html
In docs/_build/html/index.html, you'll see the function with separate sections: "Parameters", "Returns", "Return type" and the highlighted note. The language setting controls the language of those section titles; with "en", they come out in English.
To document a module variable, write a comment that starts with #: right above it. autodoc picks it up as its description:
#: Default wait time in seconds for each SSH session.
TIMEOUT = 5
epydoc --pdf. In Sphinx, you choose the format with the builder: -b latex produces LaTeX sources for PDF and -b epub an e-book. For inheritance diagrams, there's the sphinx.ext.inheritance_diagram extension, which requires Graphviz.Google and NumPy styles with napoleon
reST fields are precise, but they're somewhat hard to read in the source code. That's why many projects use 2 other styles. The sphinx.ext.napoleon extension, included with Sphinx, translates them into reST before generating the documentation.
The Google style uses indented headings such as Args:, Returns: and Raises::
def validate_vlan(vlan_id: int, reserved: set[int] | None = None) -> bool:
"""Tells whether a VLAN ID can be used.
Args:
vlan_id: VLAN number, from 1 to 4094.
reserved: IDs your network doesn't allow you to assign.
Returns:
True if the ID is valid and not reserved.
Raises:
TypeError: If vlan_id isn't an integer.
"""
if not isinstance(vlan_id, int):
raise TypeError("vlan_id must be an int")
reserved = reserved or set()
return 1 <= vlan_id <= 4094 and vlan_id not in reserved
The NumPy style uses titles underlined with hyphens (Parameters, Returns) and is common in scientific projects. Pick one style per project and stick to it. Consistency matters more than the style itself.
Type annotations as documentation
In the examples, you saw signatures like prefix: int and -> str. These are type annotations. Python doesn't check them at runtime, but they document the function's contract, and tools take advantage of them: help(), Sphinx, your editor and type checkers such as mypy.
If you annotate the types, you can leave out :type: and :rtype: in the docstring. That way you avoid repeating the same information in 2 places that can drift out of sync.
import inspect
from annotationlib import Format, get_annotations
def configure_vlan(vlan_id: int, name: str = "unnamed") -> bool:
"""Creates a VLAN on the switch."""
return True
print(inspect.signature(configure_vlan))
# In 3.14, the annotation isn't evaluated when the function is defined
def connect(device: Router) -> Session:
"""Opens a session with the device."""
print(get_annotations(connect, format=Format.STRING))
try:
get_annotations(connect) # VALUE format by default
except NameError as error:
print("NameError:", error)
class Router: ...
class Session: ...
print(get_annotations(connect)) # now they exist
(vlan_id: int, name: str = 'unnamed') -> bool
{'device': 'Router', 'return': 'Session'}
NameError: name 'Router' is not defined
{'device': <class '__main__.Router'>, 'return': <class '__main__.Session'>}
connect is defined without errors even though Router doesn't exist yet. The new annotationlib module lets you read them as values, as strings or with forward references.Challenge
Answer before you open the solution.
1. What's the practical difference between a # comment and a docstring?
The docstring stays in the object. You can read it at runtime with __doc__ or help(). The comment disappears at compile time.
2. You run python -m pydoc -k netmiko and your module doesn't show up, even though it works with netmiko. What do you check?
The first line of the module's docstring. -k only searches the synopsis. If the word isn't there, pydoc doesn't find it.
3. An old script uses :raise ValueError: and :see: for Epydoc. How do you write them for Sphinx?
:raises ValueError: and .. seealso::. The first is still a field; the second becomes a directive.
4. Your team prefers docstrings with Args: and Returns:. What does Sphinx need to understand them?
The sphinx.ext.napoleon extension. Add it to extensions in conf.py; it converts the Google and NumPy styles to reST.
5. In Python 3.14, you define def f(x: Interface): ... before creating the Interface class. Is there an error?
Not when you define it. Annotations are evaluated lazily. The NameError only appears if you ask for the annotations as values before the class exists.
Key takeaways
- A docstring is the first string in a function, class or module; it ends up in
__doc__. - PEP 257: triple double quotes, a one-line summary, a blank line and the details.
help()andpython -m pydocshow the documentation;-wgenerates HTML,-bopens the browser.- reST is the Python community's markup; Sphinx with autodoc turns it into a site.
- Epydoc is a thing of the past: its fields live on in Sphinx as
:param:,:raises:or directives. - Type annotations document too; in 3.14 they're evaluated lazily.
Documentation explains what your code should do. In the next chapter, you'll check that it really does, with automated tests.
Official resources
- PEP 257 – Docstring Conventionspeps.python.org
- pydoc — Documentation generator and online help systemdocs.python.org
- annotationlib — Functionality for introspecting annotationsdocs.python.org
- PEP 649 – Deferred Evaluation Of Annotationspeps.python.org
- Sphinx: the Python domain (info field lists)sphinx-doc.org
- sphinx.ext.napoleonsphinx-doc.org
Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.