如何在Python中记录模块?

85

就这样了。如果你想记录一个函数或一个类,你可以在定义后面加上一个字符串。例如:

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

那么模块呢?我该如何记录 file.py 的功能?


4
我刚找到这个链接:http://docs.python.org/devguide/documenting.html,希望对你有用。 - Antonio de Mora
6个回答

99

将你的文档字符串作为模块中的第一条语句添加。

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

import foo

# ...

对于包(package),您可以将文档字符串(docstring)添加到__init__.py中。


第一条语句的意思是,在模块文件中我仍然可以有注释块吗?例如,#!/usr/bin/python 行和包含版权声明的注释块仍然可以出现在模块 docstring 之前吗? - Mike Finch
1
注释不算做语句,所以在文件顶部使用 shebang 是可以的。我已经这样做了很多次,您可以通过检查模块的“__doc__”属性来验证 docstring 是否被读取。 - Brad Koch

55

27

这里有一个示例:Google风格的Python文档字符串,介绍了如何记录模块。基本上包括模块信息,如何执行它,以及模块级变量和待办事项列表。

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

8
你可以用相同的方法来完成。在模块中,将一个字符串作为第一条语句输入即可。

1
这是在创建新模块时Eclipse自动执行的操作。 - Rivka

4

对于PyPI软件包:

如果您像下面看到的那样在__init__.py文件中添加文档字符串,则可以:

"""
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”是通过将第一个文档字符串放在文件的顶部来触发的。

3

很简单,你只需要在模块顶部添加文档字符串即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接