Python docstring 必须用三重双引号,紧贴def下方无空行,首行摘要后需空一行;类型提示优先于docstring类型描述,风格(Google/NumPy)须统一。

Python docstring 用三重双引号,不是单引号或三重单引号
Python 官方 PEP 257 明确规定:docstring 必须使用三重双引号 """,即使内容只有一行。用 ''' 虽然语法不报错,但会导致部分工具(如 sphinx、pydoc、IDE 悬停提示)无法正确提取文档,pylint 也会报 C0114 警告。
常见错误现象:
- PyCharm 悬停看不到函数说明
-
help(my_function)返回None或空字符串 -
sphinx-autodoc生成文档时该函数条目空白
正确写法示例:
def add(a, b):
"""Return the sum of a and b."""
return a + b函数 docstring 必须紧贴 def 行下方,中间不能有空行
docstring 是函数对象的 __doc__ 属性值,Python 解析器只认紧随 def 语句之后、且无空行隔开的字符串字面量。一旦中间插入空行或注释,它就变成普通字符串,不再被识别为 docstring。
立即学习“Python免费学习笔记(深入)”;
容易踩的坑:
- 在
def和"""之间加了空行 →__doc__为None - 写了注释如
# 计算两数之和再换行写 docstring → 注释不算 docstring,__doc__仍为空 - 使用 f-string 或变量拼接(如
f"""...""")→ 不是字符串字面量,无效
正确结构:
def multiply(x, y):
"""Multiply x by y and return the result.
Args:
x (int or float): The first operand.
y (int or float): The second operand.
Returns:
int or float: Product of x and y.
"""
return x * yGoogle 风格 vs NumPy 风格:选一种并坚持用到底
标准库本身不强制格式,但主流工具链(sphinx.ext.napoleon、VS Code Python 扩展、Ruff)默认支持 Google 和 NumPy 两种结构化风格。混用会导致解析失败或字段丢失——比如把 Args: 写成 Parameters: 却没配对应解析器,参数列表就直接消失。
推荐选择依据:
- 团队已有代码库?沿用现有风格,别另起炉灶
- 新项目且用 Sphinx?选 NumPy 风格,
napoleon_numpy_docstring = True开箱即用 - 偏爱简洁?Google 风格字段名更短(
Args/Returns),缩进更松散
Google 风格片段示例(注意缩进对齐):
def format_name(first_name, last_name):
"""Capitalize and join first and last name.
Args:
first_name (str): Given name, case-insensitive.
last_name (str): Family name, case-insensitive.
Returns:
str: Full name with title case, e.g., "John Doe".
"""
return f"{first_name.title()} {last_name.title()}"类型提示已成主流,docstring 中的类型描述可精简但不能矛盾
Python 3.5+ 支持 def func(x: int) -> str: 这类类型提示,IDE 和静态检查工具(如 mypy)优先读取类型提示而非 docstring。如果两者冲突(例如签名写 x: int,docstring 却写 Args: x (str): ...),会误导开发者且触发 pyright 或 pylance 报错。
实操建议:
- 类型已在签名中声明 → docstring 的
Args字段里类型括号可省略,或仅作补充说明(如x: int, must be positive) - 复杂嵌套类型(如
list[dict[str, Any]])不宜全写进签名,可在 docstring 中用自然语言解释 - 返回值含多种可能(
Union[str, None])?docstring 中明确说明什么条件下返回什么
例如:
def find_user(user_id: int) -> dict | None:
"""Look up user by ID in database.
Args:
user_id: Numeric ID; must be > 0.
Returns:
User data as dict if found, otherwise None.
"""
if user_id <= 0:
return None
# ...真正容易被忽略的是:docstring 的首行摘要(summary line)必须是独立一行,且与后续详细描述之间空一行。很多开发者以为“写完一句话就完了”,结果把参数说明直接接在第一行后面,导致自动化工具只提取到前半句——因为 PEP 257 规定摘要行之后必须有空行分隔。










