Comments begin with a
PEP 8 recommends that comments should have a maximum line length of 72 characters. Comments longer than this should be split into multiple lines.
A docstring is an official way of in-place Python code documentation. It takes the form of blocks of text starting and ended with
""" placed throughout the code.
When these comments are in the correct places, the Python bytecode compiler recognizes them and adds them to the
__doc__ parameter which can be inspected at runtime.
Python recognizes docstrings when the are placed at the start of functions, classes, modules (e.g. at the top of Python files and the directory also contains an
__init__.py) and also when in the
__init__.py file of a Python package.
A docstring is formally defined by PEP 257 as:
A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the
__doc__special attribute of that object.
Try to use
""" for delimiting docstrings, and never
''' (purely for consistency). If your docstrings need to contain backslashes you can use
r""", if you need to include unicode characters you can use
There are a few popular docstring styled used.
This is the official Python documentation style. It is feature rich, but not a simple as the Google style.
Args can be replaced with
reStructured Text Style
The reStructured text style is used by Sphinx to generate documentation (however Sphinx can also handle Google-style docstrings with the pre-packaged Napoleon extension). It is the default docstrings style when using the JetBrains PyCharm IDE (although the IDE supports the other common styles also).
Notice how the type for each parameter has to be specified on it’s own line with the
rtype identifiers, which is rather clunky!
Docutils is a tool you can use to generate documentation from Python docstrings.
This work is licensed under a Creative Commons Attribution 4.0 International License .