How to document a method with parameter(s)?

前端 未结 8 1767
情书的邮戳
情书的邮戳 2020-12-07 07:52

How to document methods with parameters using Python\'s documentation strings?

EDIT: PEP 257 gives this example:

d         


        
相关标签:
8条回答
  • 2020-12-07 08:00

    Conventions:

    • PEP 257 Docstring Conventions
    • PEP 287 reStructuredText Docstring Format

    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.

    0 讨论(0)
  • 2020-12-07 08:06

    The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

    That being said, I personally go with inline comment style occasionally.

    def complex(  # Form a complex number
            real=0.0,  # the real part (default 0.0)
            imag=0.0  # the imaginary part (default 0.0)
            ):  # Returns a complex number.
        """Form a complex number.
    
        I may still use the mainstream docstring notation,
        if I foresee a need to use some other tools
        to generate an HTML online doc later
        """
        if imag == 0.0 and real == 0.0:
            return complex_zero
        other_code()
    

    One more example here, with some tiny details documented inline:

    def foo(  # Note that how I use the parenthesis rather than backslash "\"
              # to natually break the function definition into multiple lines.
            a_very_long_parameter_name,
                # The "inline" text does not really have to be at same line,
                # when your parameter name is very long.
                # Besides, you can use this way to have multiple lines doc too.
                # The one extra level indentation here natually matches the
                # original Python indentation style.
                #
                # This parameter represents blah blah
                # blah blah
                # blah blah
            param_b,  # Some description about parameter B.
                # Some more description about parameter B.
                # As you probably noticed, the vertical alignment of pound sign
                # is less a concern IMHO, as long as your docs are intuitively
                # readable.
            last_param,  # As a side note, you can use an optional comma for
                         # your last parameter, as you can do in multi-line list
                         # or dict declaration.
            ):  # So this ending parenthesis occupying its own line provides a
                # perfect chance to use inline doc to document the return value,
                # despite of its unhappy face appearance. :)
        pass
    

    The benefits (as @mark-horvath already pointed out in another comment) are:

    • Most importantly, parameters and their doc always stay together, which brings the following benefits:
    • Less typing (no need to repeat variable name)
    • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
    • and easier to find missing comment.

    Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

    Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

    PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

    0 讨论(0)
  • 2020-12-07 08:09

    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.

    0 讨论(0)
  • 2020-12-07 08:09

    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

    0 讨论(0)
  • 2020-12-07 08:12

    Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:

    def copy_net(
        infile: (str, 'The name of the file to send'),
        host: (str, 'The host to send the file to'),
        port: (int, 'The port to connect to')):
    
        pass
    

    example adopted from: https://pypi.org/project/autocommand/

    0 讨论(0)
  • 2020-12-07 08:14

    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`.
    
    0 讨论(0)
提交回复
热议问题