docstring of python

sphinx usages

https://brendanhasz.github.io/2019/01/05/sphinx.html#file-hierarchy

    sphinx可以从python文档中自动提取docstring生成文档。

   docstring包括函数和类的注释。

理解:

   sphinx在手动维护的独立文档,非代码文档之外, 代码中的注释也可以被集成到软件文档中。

    这是sphinx强大的能力, 也践行了代码即文档的理念, 确保代码和文档具有一致性。

   在此工具之前,往往描述代码的文档是独立于代码的另一份文档。

The autodoc extension for sphinx can automatically generate API reference doc pages from the docstrings in your python code. Python docstrings are string literals which occur immediately after function or class definitions. They’re treated as comments, and it’s customary to document a function or class in its docstring. The autodoc extension allows you to include reStructuredText in your docstrings, and will build an API reference automatically for your module from the docstrings, while allowing for further customization.

在rst文件中,可以通过 automodule指令来提取文档注释。

Automodule and autoclass

After enabling autodoc, in the documentation’s .rst files, you can use the automodule directive:

.. automodule:: package_name.module
   :members:

which will insert an automatically generated API reference for the entire module. The :members: role makes autodoc generate documentation for each member (function, class, or constant) in that module, and for each member of each class (attributes and methods).

To insert an automatically-generated API reference only for one specific class, you can use the autoclass directive:

.. autoclass:: package_name.module.class_name
   :members:
   :inherited-members:
   :exclude-members: members, to, exclude

which lists all attributes and methods, except those in the exclude-members list.

The :inherited-members: role causes members which are inherited to also be included in the documentation (this role can also be used with automodule).

Speaking of inheritance, to show a list of classes the current class inherits from , add the :show-inheritance: role to the directive.

To include only specific members, instead of specifying :exclude-members:, you can add a list of members you do want to include after :members:, eg: :members: members, to, include.

Docstring Conventions

https://www.python.org/dev/peps/pep-0257/

      统一的规定提供软件工程的灵魂, 可维护性, 清晰性, 一致性。

Rationale

The aim of this PEP is to standardize the high-level structure of docstrings: what they should contain, and how to say it (without touching on any markup syntax within docstrings). The PEP contains conventions, not laws or syntax.

"A universal convention supplies all of maintainability, clarity, consistency, and a foundation for good programming habits too. What it doesn't do is insist that you follow it against your will. That's Python!"

—Tim Peters on comp.lang.python, 2001-06-16

     docstring是字符文本, 出现在 模块、函数、类、方法的定义之后。

    加载后被存储在 __doc__ 属性中。

What is a Docstring?

A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__), but two types of extra docstrings may be extracted by software tools:

  1. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".
  2. String literals occurring immediately after another docstring are called "additional docstrings".

单行docstring

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root

多行docstring

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

与#差别

#注释不加载到内存, docstring会被加载到内存,可以在运行时获取到。

理解docstring设计可能又三个方面原因:

(1)docstring应该是python做的自省的方法, 可以让代码在运行的之后,知道是什么样的代码在运行。

(2)有助于开发者查阅文档。

(3)有助于debug。

https://www.programiz.com/python-programming/docstrings

Python Comments vs Docstrings

Python Comments

Comments are descriptions that help programmers better understand the intent and functionality of the program. They are completely ignored by the Python interpreter.

In Python, we use the hash symbol # to write a single-line comment. For example,

# Program to print "Hello World"
print("Hello World") 

Python Comments Using Strings

If we do not assign strings to any variable, they act as comments. For example,

"I am a single-line comment"

'''
I am a
multi-line comment!
'''

print("Hello World")

Note: We use triple quotation marks for multi-line strings.

Python docstrings

As mentioned above, Python docstrings are strings used right after the definition of a function, method, class, or module (like in Example 1). They are used to document our code.

We can access these docstrings using the __doc__ attribute.

例如使用 __doc__ 属性来获取。

Python __doc__ attribute

Whenever string literals are present just after the definition of a function, module, class or method, they are associated with the object as their __doc__ attribute. We can later use this attribute to retrieve this docstring.

Example 2: Printing docstring

def square(n):
    '''Takes in a number n, returns the square of n'''
    return n**2

print(square.__doc__)

Output

Takes in a number n, returns the square of n

Here, the documentation of our square() function can be accessed using the __doc__ attribute.

使用help函数也可以获取。

Using the help() Function for Docstrings

We can also use the help() function to read the docstrings associated with various objects.

Example 7: Read Docstrings with the help() function

We can use the help() function on the class Person in Example 6 as:

help(Person)

Output

Help on class Person in module __main__:

class Person(builtins.object)
 |  Person(name, surname, age)
 |  
 |  A class to represent a person.
 |  
 |  ...
 |  
 |  Attributes
 |  ----------
 |  name : str
 |      first name of the person
 |  surname : str
 |      family name of the person
 |  age : int
 |      age of the person
 |  
 |  Methods
 |  -------
 |  info(additional=""):
 |      Prints the person's name and age.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, name, surname, age)
 |      Constructs all the necessary attributes for the person object.
 |      
 |      Parameters
 |      ----------
 |          name : str
 |              first name of the person
 |          surname : str
 |              family name of the person
 |          age : int
 |              age of the person
 |  
 |  info(self, additional='')
 |      Prints the person's name and age.
 |      
 |      If the argument 'additional' is passed, then it is appended after the main info.
 |      
 |      Parameters
 |      ----------
 |      additional : str, optional
 |          More info to be displayed (default is None)
 |      
 |      Returns
 |      -------
 |      None
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Here, we can see that the help() function retrieves the docstrings of the Person class along with the methods associated with that class.


原文地址:https://www.cnblogs.com/lightsong/p/14267839.html