在非标准上下文中使用三引号创建 "docstrings" 是一种好习惯吗?

Is it a good practice to use triple quotes to create "docstrings" in non-standard contexts?

我正在查看某人的代码,其中到处都是这种 "docstrings":

SLEEP_TIME_ON_FAILURE = 5
"""Time to keep the connection open in case of failure."""

SOCKET_TIMEOUT = 15
"""Socket timeout for inherited socket."""

...

根据 Python 文档,文档字符串仅适用于模块开头的上下文、class 或方法。

上述不规范的做法意味着什么?为什么 Python 允许这样做?这不会影响性能吗?

在这些情况下,您应该使用内联注释,PEP8 风格指南明确定义了 https://www.python.org/dev/peps/pep-0008/#comments,例如:

SLEEP_TIME_ON_FAILURE = 5  # Time to keep the connection open in case of failure

SOCKET_TIMEOUT = 15  # Socket timeout for inherited socket

在 python 中,""" 是多行字符串的语法。

s1 = """This is a multi-line string."""
s2 = """This is also a multi-line
string that stretches 
across multiple lines"""

如果这些字符串没有存储到变量中,那么它们会立即被垃圾回收,并且基本上被忽略,但它们仍然会占用一些开销。另一方面,使用 # 的注释实际上会被解释器完全忽略。

此规则的唯一例外是此文档字符串紧跟在 函数或 class 定义 之后,或位于 模块 。在这种情况下,它存储在特殊变量 __doc__.

根据PEP8

Documentation Strings Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in PEP 257.

Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the def line.

就 Python 而言,这些不是文档字符串。它们只是用作表达式语句的字符串文字。你可以这样做——你可以使用任何有效的 Python 表达式作为它自己的语句。 Python 不关心表达式是否实际执行任何操作。对于单独一行的字符串,唯一的性能影响是字节码编译时的少量额外工作;在运行时没有影响,因为这些字符串得到了优化。

一些文档生成器会查看这些字符串。例如,非常常见的 Sphinx autodoc 扩展将解析这些字符串以记录它们正上方的任何内容。在更改代码之前检查您是否正在使用类似的东西。