How to document a method with parameter(s)?

182,076

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:


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

Share:
182,076

Related videos on Youtube

David Andreoletti
Author by

David Andreoletti

I am a Python/Java/C/C++/ObjC software engineer Sites Blog Linkedin

Updated on July 08, 2022

Comments

  • David Andreoletti
    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
      NPE over 12 years
      Have you read PEP 257? python.org/dev/peps/pep-0257
    • jojo
      jojo about 10 years
      There are several 'standards' out there but on a practical approach and especially if you like something formal, I would recommend sphinx. Its integration in Pycharm makes generating well structured docstrings rather painless. IMHO
  • David Andreoletti
    David Andreoletti about 12 years
    This 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
    koriander almost 11 years
    Although 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
    Brandon Rhodes over 10 years
    When I attempt processing your suggested docstring, Sphinx complains SEVERE: Unexpected section title — do you know any way to make Sphinx happier about it?
  • David
    David over 9 years
    Ugly yes? Interesting idea... also yes.
  • Mark Horvath
    Mark Horvath about 9 years
    Inline 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
    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.tx‌​t
  • Zelphir Kaltstahl
    Zelphir Kaltstahl about 8 years
    Actually 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
    Josiah Yoder almost 7 years
    This is the style used by PyCharm's comment autogeneration by default
  • Alex L
    Alex L over 6 years
    This 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
    Admin about 6 years
    That 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
    Michael Walters about 6 years
    This is just awful.
  • matanster
    matanster almost 6 years
    What about the syntax of composite types like lists of stuff?
  • anarcat
    anarcat almost 6 years
    then it's a list.
  • Ofri Raviv
    Ofri Raviv over 4 years
    Is this an official syntax? Its super useful, however I can't find it in the official docs/PEPs...
  • DreamFlasher
    DreamFlasher over 4 years
    I'd like to know that too, if there is a PEP for it.
  • Ivan Vučica
    Ivan Vučica almost 3 years
    This 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
    jcdude over 2 years
    I 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
    B. Fuller about 2 years
    The link in @BrandonRhodes comment is now broken. Now here: numpydoc.readthedocs.io/en/latest/…
  • Ereghard
    Ereghard about 2 years
    I don't know why they don't recommend putting empty line between each parameter-type pair. This is so ugly.
  • alper
    alper about 2 years
    @Ereghard being compact is always better, you will get used to it over time.