Basic Syntax of comments and docstrings in Python code

天涯浪子 提交于 2020-07-09 12:04:52

问题


I'm learning how to use Sphinx to create a documentation for my code. After I saw some examples like this:

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
    ...

What is the language used in comments to make Sphinx understand and catch them? Without this syntax and logic, Sphinx doesn't see the comments in my code and when I generate the HTML, the module is empty.

Here an example:


回答1:


You have to distinguish comments from docstrings (called "documentation strings" in full).

See PEP8 and notice docstrings apply only to modules, functions, classes, and methods. To the mentioned objects you can apply your_object.__doc__ to retrieve the docstring programmatically; Variables don't have docstrings.

Regarding your 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)

    """

There are 3 prevalent syntaxes that can be used in docstring that Sphinx will retrieve:

  1. reST is the basic syntax.
  2. Numpy-style docstrings.
  3. Google-style docstrings.

The norm is to choose between Numpy or Google style (currently they provide better readability and functionality, together with a style guide). For these to work you'll need to use the Sphinx-Napoleon extension, take a look at the overview in the official documentation.



来源:https://stackoverflow.com/questions/62545038/basic-syntax-of-comments-and-docstrings-in-python-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!