如何用 Python 编写模块文档?

就是这样。如果你想记录一个函数或者类,你可以在定义之后放一个字符串。例如:

def foo():
"""This function does nothing."""
pass

但是一个模块怎么样呢? 我如何记录 File.py的功能呢?

63856 次浏览

很简单,只需在模块的顶部添加一个 docstring。

对于包,您可以用 __init__.py记录它。 对于模块,您可以在模块文件中简单地添加一个 docstring。

所有信息都在这里: http://www.python.org/dev/peps/pep-0257/

完全按照相同的方法执行。在模块中放入一个字符串作为第一条语句。

添加文档字符串作为 模块中的第一个语句

"""
Your module's verbose yet thorough docstring.
"""


import foo


# ...

对于包,可以将 docstring 添加到 __init__.py

下面是一个关于如何记录模块的 示例 Google 样式 Python 文档字符串。基本上有关于一个模块的信息,如何执行它,以及关于模块级别变量和 ToDo 项目列表的信息。

"""Example Google style docstrings.


This module demonstrates documentation as specified by the `Google
Python Style Guide`_. Docstrings may extend over multiple lines.
Sections are created with a section header and a colon followed by a
block of indented text.


Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::


$ python example_google.py


Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.


Attributes:
module_level_variable1 (int): Module level variables may be documented in
either the ``Attributes`` section of the module docstring, or in an
inline docstring immediately following the variable.


Either form is acceptable, but the two should not be mixed. Choose
one convention to document module level variables and be consistent
with it.


Todo:
* For module TODOs
* You have to also use ``sphinx.ext.todo`` extension


.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html


"""


module_level_variable1 = 12345


def my_function():
pass
...
...

对于 PyPI 包:

如果在 不,不,不,不,不,不,不,不,不,不,不,不,不文件中像这样添加 doc 字符串,如下所示

"""
Please refer to the documentation provided in the README.md,
which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/
"""


# <IMPORT_DEPENDENCIES>


def setup():
"""Verify your Python and R dependencies."""

然后您将在帮助函数的日常使用中收到此信息。

help(<YOUR_PACKAGE>)

DESCRIPTION
Please refer to the documentation provided in the README.md,
which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/




FUNCTIONS
setup()
Verify your Python and R dependencies.

注意,我的帮助 DESCRIPTION是由文件顶部的第一个 docstring 触发的。