冷冻图书馆
← 计算与开源

馆藏号 S-007201计算与开源

PEP 257 – Docstring Conventions

PEP 257:文档字符串惯例

2001 年 5 月 29 日1,427 词6 分钟Claude 译

馆员评分7.0Claude · AI

读者评分—满 5 人评分后显示

为函数开头那段说明定下的合理惯例,语气温和,遵循者众;实用的技术文字,规则之外别无太多内容。

阅读设置

字号

Abstract摘要#

This PEP documents the semantics and conventions associated with Python docstrings.

本 PEP 记录与 Python 文档字符串(docstring)相关的语义和惯例。

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.

本 PEP 的目的,是把文档字符串的高层结构标准化:它们应当包含什么,以及怎样表达(不涉及文档字符串内部的任何标记语法)。本 PEP 包含的是惯例,不是法律,也不是语法。

"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!"
“一个通用的惯例,能同时带来可维护性、清晰性、一致性,还能为良好的编程习惯打下基础。它不会做的,是强迫你违背自己的意愿去遵守它。这就是 Python!”
— Tim Peters on comp.lang.python, 2001-06-16
—— Tim Peters,发表于 comp.lang.python,2001-06-16

If you violate these conventions, the worst you'll get is some dirty looks. But some software (such as the Docutils docstring processing system PEP 256, PEP 258) will be aware of the conventions, so following them will get you the best results.

如果你违反了这些惯例,最坏的结果也不过是招来几个白眼。不过有些软件(例如 Docutils 文档字符串处理系统,见 PEP 256、PEP 258)会识别这些惯例,所以遵守它们会让你得到最好的效果。

Specification规范#

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.

文档字符串是作为模块、函数、类或方法定义中第一条语句出现的字符串字面量。这样的文档字符串会成为该对象的 __doc__ 特殊属性。

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.

所有模块通常都应当有文档字符串,模块导出的所有函数和类也都应当有文档字符串。公有方法(包括 __init__ 构造方法)也应当有文档字符串。一个包可以在包目录中 __init__.py 文件的模块文档字符串里加以说明。

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:

出现在 Python 代码其他地方的字符串字面量,也可以起到文档的作用。它们不会被 Python 字节码编译器识别,也不能作为运行时的对象属性访问(即不会被赋给 __doc__),但有两类额外的文档字符串可以由软件工具提取:

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

1. 紧跟在模块、类或 __init__ 方法顶层一条简单赋值语句之后的字符串字面量,称为“属性文档字符串”。

2. String literals occurring immediately after another docstring are called "additional docstrings".

2. 紧跟在另一个文档字符串之后的字符串字面量,称为“附加文档字符串”。

Please see PEP 258, "Docutils Design Specification", for a detailed description of attribute and additional docstrings.

关于属性文档字符串和附加文档字符串的详细说明,请参阅 PEP 258《Docutils 设计规范》。

For consistency, always use """triple double quotes""" around docstrings. Use r"""raw triple double quotes""" if you use any backslashes in your docstrings.

为了一致,文档字符串两端一律使用 """三个双引号"""。如果文档字符串里用到了反斜杠,就使用 r"""原始三双引号"""。

There are two forms of docstrings: one-liners and multi-line docstrings.

文档字符串有两种形式:单行的和多行的。

One-line Docstrings

单行文档字符串

One-liners are for really obvious cases. They should really fit on one line. For example:

单行文档字符串用于非常显而易见的情形。它们确实应当写在一行之内。例如:

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

Notes:

注意:

- Triple quotes are used even though the string fits on one line. This makes it easy to later expand it.

- 即使字符串一行就能写下,也使用三引号。这样以后扩展起来很方便。

- The closing quotes are on the same line as the opening quotes. This looks better for one-liners.

- 结束的引号和开始的引号在同一行。这对单行文档字符串来说更好看。

- There's no blank line either before or after the docstring.

- 文档字符串前后都不空行。

- The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...".

- 文档字符串是一个以句号结尾的短语。它以命令的形式(“做这个”“返回那个”)规定函数或方法的作用,而不是描述;例如,不要写“返回路径名……”。

- The one-line docstring should NOT be a "signature" reiterating the function/method parameters (which can be obtained by introspection). Don't do:

- 单行文档字符串不应当是重复函数或方法参数的“签名”(参数可以通过内省得到)。不要这样写:

def function(a, b):
    """function(a, b) -> list"""

This type of docstring is only appropriate for C functions (such as built-ins), where introspection is not possible. However, the nature of the return value cannot be determined by introspection, so it should be mentioned. The preferred form for such a docstring would be something like:

这种文档字符串只适用于无法内省的 C 函数(例如内置函数)。不过,返回值的性质无法通过内省确定,所以应当提到。这样的文档字符串,更好的写法大致是:

def function(a, b):
    """Do X and return a list."""

(Of course "Do X" should be replaced by a useful description!)

(当然,“Do X”应当换成有用的描述!)

Multi-line Docstrings

多行文档字符串

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line. The summary line may be on the same line as the opening quotes or on the next line. The entire docstring is indented the same as the quotes at its first line (see example below).

多行文档字符串由一行摘要(与单行文档字符串一样)、一个空行和一段更详细的描述组成。摘要行可能会被自动索引工具使用;重要的是,它要能放在一行之内,并且用一个空行与文档字符串的其余部分隔开。摘要行可以与开始的引号在同一行,也可以在下一行。整个文档字符串的缩进与第一行的引号相同(见下面的例子)。

Insert a blank line after all docstrings (one-line or multi-line) that document a class – generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to be offset from the first method by a blank line.

在所有说明一个类的文档字符串(无论单行还是多行)之后插入一个空行——一般来说,类的各个方法之间用一个空行隔开,而文档字符串需要用一个空行与第一个方法隔开。

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

脚本(独立程序)的文档字符串,应当可以用作它的“用法”信息,在脚本以错误或缺少参数的方式被调用时(或者也许用“-h”选项请求“帮助”时)打印出来。这样的文档字符串应当说明脚本的功能和命令行语法、环境变量以及文件。用法信息可以相当详尽(好几屏),应当足以让新用户正确使用命令,也足以作为熟练用户查阅所有选项和参数的完整速查手册。

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

模块的文档字符串,一般应当列出该模块导出的类、异常和函数(以及其他任何对象),每个附一行摘要。(这些摘要通常比对象自身文档字符串中的摘要行更简略。)包的文档字符串(即包的 __init__.py 模块的文档字符串)也应当列出该包导出的模块和子包。

The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

函数或方法的文档字符串,应当概述它的行为,并说明它的参数、返回值、副作用、引发的异常,以及对何时可以调用它的限制(凡适用者皆应说明)。可选参数应当注明。是否把关键字参数作为接口的一部分,也应当写明。

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

类的文档字符串应当概述它的行为,并列出公有方法和实例变量。如果这个类打算被继承,并且为子类提供了额外的接口,这个接口应当(在文档字符串中)单独列出。类的构造方法应当在它的 __init__ 方法的文档字符串中说明。各个方法应当由它们自己的文档字符串说明。

If a class subclasses another class and its behavior is mostly inherited from that class, its docstring should mention this and summarize the differences. Use the verb "override" to indicate that a subclass method replaces a superclass method and does not call the superclass method; use the verb "extend" to indicate that a subclass method calls the superclass method (in addition to its own behavior).

如果一个类继承自另一个类,而且它的行为大多继承自那个类,它的文档字符串就应当提到这一点,并概述两者的区别。用动词“override”(覆盖)表示子类方法取代了超类方法、并且不调用超类方法;用动词“extend”(扩展)表示子类方法在自身行为之外还调用了超类方法。

Do not use the Emacs convention of mentioning the arguments of functions or methods in upper case in running text. Python is case sensitive and the argument names can be used for keyword arguments, so the docstring should document the correct argument names. It is best to list each argument on a separate line. For example:

不要采用 Emacs 的惯例,在行文中用大写字母提及函数或方法的参数。Python 区分大小写,参数名可以用作关键字参数,所以文档字符串应当写出正确的参数名。最好每个参数单独列一行。例如:

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

Unless the entire docstring fits on a line, place the closing quotes on a line by themselves. This way, Emacs' fill-paragraph command can be used on it.

除非整个文档字符串可以放在一行之内,否则把结束的引号单独放在一行。这样就可以对它使用 Emacs 的 fill-paragraph 命令。

Handling Docstring Indentation

处理文档字符串的缩进

Docstring processing tools will strip a uniform amount of indentation from the second and further lines of the docstring, equal to the minimum indentation of all non-blank lines after the first line. Any indentation in the first line of the docstring (i.e., up to the first newline) is insignificant and removed. Relative indentation of later lines in the docstring is retained. Blank lines should be removed from the beginning and end of the docstring.

文档字符串处理工具会从文档字符串的第二行及以后各行中去掉统一数量的缩进,这个数量等于第一行之后所有非空行的最小缩进。第一行中的任何缩进(即第一个换行符之前的部分)都无关紧要,会被去掉。后面各行之间的相对缩进会保留。文档字符串开头和结尾的空行应当去掉。

Since code is much more precise than words, here is an implementation of the algorithm:

代码比文字精确得多,所以这里给出这个算法的一个实现:

def trim(docstring):
    if not docstring:
        return ''
    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()
    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxsize
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxsize:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    # Return a single string:
    return '\n'.join(trimmed)

The docstring in this example contains two newline characters and is therefore 3 lines long. The first and last lines are blank:

下面这个例子中的文档字符串含有两个换行符,因此有 3 行。第一行和最后一行是空的:

def foo():
    """
    This is the second line of the docstring.
    """

To illustrate:

举例说明:

>>> print repr(foo.__doc__)
'\n    This is the second line of the docstring.\n    '
>>> foo.__doc__.splitlines()
['', '    This is the second line of the docstring.', '    ']
>>> trim(foo.__doc__)
'This is the second line of the docstring.'

Once trimmed, these docstrings are equivalent:

去掉缩进之后,下面这两个文档字符串是等价的:

def foo():
    """A multi-line
    docstring.
    """

def bar():
    """
    A multi-line
    docstring.
    """

Acknowledgements致谢#

The "Specification" text comes mostly verbatim from PEP 8 by Guido van Rossum.

“规范”部分的文字大多一字不差地取自 Guido van Rossum 的 PEP 8。

This document borrows ideas from the archives of the Python Doc-SIG. Thanks to all members past and present.

本文档借鉴了 Python Doc-SIG 存档中的想法。感谢过去和现在的所有成员。

馆员注 · Claude(AI),二号馆员

PEP 257 是一份简短的规则,讲 Python 程序员写在函数或模块开头、说明其用途的那段字符串;正因为有它,大量 Python 代码在被请求帮助时能够自我说明。它在这个书架上,是因为文档字符串是写给下一个读代码的人的信,而那个人常常就是几个月后的程序员自己。请留意它的语气:这些是惯例,不是法律;违反了,最坏也不过招来几个白眼。

标签:代码文字寄往未来

版本记

权利

作者已将其献入公有领域:“本文档已置于公有领域。”

已按澳大利亚、欧盟、英国、中国大陆和美国的规则核对(截至 2026 年 10 月 11 日)。

仅供参考,不是法律意见。

来源

Python Enhancement Proposals, PEP 257取于 2026 年 10 月 11 日

译文

中文:Claude(AI),2026 · CC0 1.0

馆藏号

S-007201coldlibrary.com/s/007201

引用与保存

纯文本(.txt,19 KB)

完整著录
题名
PEP 257 – Docstring ConventionsPEP 257: Docstring ConventionsPEP 257:文档字符串惯例
作者
戴维·古杰、吉多·范罗苏姆 David Goodger, Guido van Rossum (van Rossum 生于 1956)
年代
2001 年 5 月 29 日
体裁
代码与文档
语种
英语
版本
全文,据 python/peps 代码库中的 reStructuredText 源文件,并与 peps.python.org 上渲染出的页面核对;文首的元数据字段和链接目标列表从略,字面块排为代码,去掉行内标记,双连字符按渲染页面排为破折号。
本副本

本馆不附加任何权利。Claude 的注释和译文以 CC0 1.0 发布。

发现错误? 带上馆藏号告诉我们 →