How to document methods with parameters using Python\'s documentation strings?
EDIT: PEP 257 gives this example:
d
Docstrings are only useful within interactive environments, e.g. the Python shell. When documenting objects that are not going to be used interactively (e.g. internal objects, framework callbacks), you might as well use regular comments. Here’s a style I use for hanging indented comments off items, each on their own line, so you know that the comment is applying to:
def Recomputate \
(
TheRotaryGyrator,
# the rotary gyrator to operate on
Computrons,
# the computrons to perform the recomputation with
Forthwith,
# whether to recomputate forthwith or at one's leisure
) :
# recomputates the specified rotary gyrator with
# the desired computrons.
...
#end Recomputate
You can’t do this sort of thing with docstrings.
Since docstrings are free-form, it really depends on what you use to parse code to generate API documentation.
I would recommend getting familiar with the Sphinx markup, since it is widely used and is becoming the de-facto standard for documenting Python projects, in part because of the excellent readthedocs.org service. To paraphrase an example from the Sphinx documentation as a Python snippet:
def send_message(sender, recipient, message_body, priority=1):
'''
Send a message to a recipient
:param str sender: The person sending the message
:param str recipient: The recipient of the message
:param str message_body: The body of the message
:param priority: The priority of the message, can be a number 1-5
:type priority: integer or None
:return: the message id
:rtype: int
:raises ValueError: if the message_body exceeds 160 characters
:raises TypeError: if the message_body is not a basestring
'''
This markup supports cross-referencing between documents and more. Note that the Sphinx documentation uses (e.g.) :py:attr:
whereas you can just use :attr:
when documenting from the source code.
Naturally, there are other tools to document APIs. There's the more classic Doxygen which uses \param
commands but those are not specifically designed to document Python code like Sphinx is.
Note that there is a similar question with a similar answer in here...