How to document a method with parameter(s)?
Solution 1
Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.
One example:
Parameters
----------
x : type
Description of parameter `x`.
Solution 2
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) -> int:
"""
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...
Solution 3
Conventions:
Tools:
- Epydoc: Automatic API Documentation Generation for Python
- sphinx.ext.autodoc – Include documentation from docstrings
- PyCharm has some nice support for docstrings
Update: Since Python 3.5 you can use type hints which is a compact, machine-readable syntax:
from typing import Dict, Union
def foo(i: int, d: Dict[str, Union[str, int]]) -> int:
"""
Explanation: this function takes two arguments: `i` and `d`.
`i` is annotated simply as `int`. `d` is a dictionary with `str` keys
and values that can be either `str` or `int`.
The return type is `int`.
"""
The main advantage of this syntax is that it is defined by the language and that it's unambiguous, so tools like PyCharm can easily take advantage from it.
Solution 4
python doc strings are free-form, you can document it in any way you like.
Examples:
def mymethod(self, foo, bars):
"""
Does neat stuff!
Parameters:
foo - a foo of type FooType to bar with.
bars - The list of bars
"""
Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.
Solution 5
If you plan to use Sphinx to document your code, it is capable of producing nicely formatted HTML docs for your parameters with their 'signatures' feature. http://sphinx-doc.org/domains.html#signatures
Related videos on Youtube
David Andreoletti
I am a Python/Java/C/C++/ObjC software engineer Sites Blog Linkedin
Updated on July 08, 2022Comments
-
David Andreoletti almost 2 years
How to document methods with parameters using Python's documentation strings?
EDIT: PEP 257 gives this example:
def complex(real=0.0, imag=0.0): """Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ...
Is this the convention used by most Python developers ?
Keyword arguments: <parameter name> -- Definition (default value if any)
I was expecting something a little bit more formal such as
def complex(real=0.0, imag=0.0): """Form a complex number. @param: real The real part (default 0.0) @param: imag The imaginary part (default 0.0) """ if imag == 0.0 and real == 0.0: return complex_zero ...
Environment: Python 2.7.1
-
NPE over 12 yearsHave you read PEP 257? python.org/dev/peps/pep-0257
-
jojo about 10 years
-
-
David Andreoletti about 12 yearsThis is closer to what I expected. Unfortunately, I picked plain PEP 257 and added my own convention (at the cost of loosing autogenerated HTML/PDF documentation). However, next time, I will pick this solution. Thanks.
-
koriander almost 11 yearsAlthough this answer is now the most upvoted, neither of the PEPs above provides a convention to specify the types of arguments of a method.
-
Brandon Rhodes over 10 yearsWhen I attempt processing your suggested docstring, Sphinx complains
SEVERE: Unexpected section title
— do you know any way to make Sphinx happier about it? -
David over 9 yearsUgly yes? Interesting idea... also yes.
-
Mark Horvath about 9 yearsInline comments for the variables is very sensible, less typing (no need to repeat variable name), easier maintenance upon changing/removing variable... easier to find missing comment. Would combine it with proper docstring below the signature. +1
-
Vladimir Keleshev about 9 years@BrandonRhodes this links talks about using these conventions with Sphinx: github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
-
Zelphir Kaltstahl about 8 yearsActually there is a space missing before
Description
. I checked the numpy documentation, because I immediately noticed and thought "Wait a second, why is it three spaces? That's odd. Who'd use three spaces?" -
Josiah Yoder almost 7 yearsThis is the style used by PyCharm's comment autogeneration by default
-
Alex L over 6 yearsThis may have been the best answer at the time the question was asked, but I think as of now (late 2017), Sphinx has emerged victorious.
-
Admin about 6 yearsThat doesn't work as documentation. If you comment your package like this and a PyCharm user downloads it, they won't be able to check what each param does without accessing your documentation - which you won't be able to generate with any software. Unless you make your own. That's why OP asks for specifying it in docstring. Sorry so late.
-
Michael Walters about 6 yearsThis is just awful.
-
matanster almost 6 yearsWhat about the syntax of composite types like lists of stuff?
-
anarcat almost 6 yearsthen it's a
list
. -
Ofri Raviv over 4 yearsIs this an official syntax? Its super useful, however I can't find it in the official docs/PEPs...
-
DreamFlasher over 4 yearsI'd like to know that too, if there is a PEP for it.
-
Ivan Vučica almost 3 yearsThis seems like it would mean "a tuple of two elements: a string and a literal string, a typing.Literal, with text "The name of the file to send"' -- this is also how pyright is interpreting it. While possibly nice, unless a PEP is explicitly adopted to allow this in the future, I don't think this is the right answer.
-
jcdude over 2 yearsI think this a neat way to do it. A big advantage is that the parameter and its doc are in the same place, which is helpful if you refactor things/change type annotations etc - you don't need to keep two different lists of stuff in sync. I hope a doc generator tool for doing it this way gets built!
-
B. Fuller about 2 yearsThe link in @BrandonRhodes comment is now broken. Now here: numpydoc.readthedocs.io/en/latest/…
-
Ereghard about 2 yearsI don't know why they don't recommend putting empty line between each parameter-type pair. This is so ugly.
-
alper about 2 years@Ereghard being compact is always better, you will get used to it over time.