Python函数注释推荐用docstring,写在函数定义下方首行缩进内、三重引号包裹,是可被help()和Sphinx等工具提取的正式文档;单行适用于简单函数,三行(含空行)适用于复杂函数,推荐Google或NumPy风格,需注意位置、格式、类型提示与语义补充,并避免冗余。

Python函数注释推荐用 docstring(文档字符串),写在函数定义下方、首行缩进内,用三重引号包裹。它不是普通注释,而是会被 Python 解析器识别、可被 help() 和文档生成工具(如 Sphinx)提取的正式文档。
基本格式:简洁清晰的单行或三行结构
简单函数用单行 docstring,直接说明“做什么”:
def add(a, b):
"""Return the sum of a and b."""
return a + b
复杂函数建议用三行格式(Google 或 NumPy 风格更常见):
- 第一行:简明功能描述(句末不加句号也可,但保持项目内统一)
- 第二行:空行(必须,否则工具可能解析异常)
- 第三行起:参数、返回值、异常等详细说明(按规范组织)
常用规范:Google 风格 vs NumPy 风格
Google 风格(易读、适合大多数项目):
立即学习“Python免费学习笔记(深入)”;
def fetch_user(user_id: int) -> dict:
"""Fetch user data by ID.
<pre class="brush:php;toolbar:false;">Args:
user_id: Unique identifier for the user.
Returns:
A dictionary containing user name, email, and join date.
Raises:
ValueError: If user_id is negative.
ConnectionError: If remote API is unreachable.
"""
...NumPy 风格(字段对齐、适合科学计算类库):
def smooth_signal(data, window_size):
"""
Apply moving average smoothing to a 1D signal.
<pre class="brush:php;toolbar:false;">Parameters
----------
data : ndarray
Input 1D array of numeric values.
window_size : int
Size of the averaging window (must be odd and >= 3).
Returns
-------
ndarray
Smoothed 1D array of same length as `data`.
Raises
------
ValueError
If `window_size` is even or less than 3.
"""
...关键细节:别踩这些坑
- docstring 必须是函数体内的第一个语句,不能被变量赋值、注释或其他代码隔开
- 不要用
#注释代替 docstring —— 它不会被help()显示,也不被 IDE 智能提示识别 - 参数类型建议用类型提示(
def func(x: str) -> int:),docstring 中可补充语义说明(如“路径需为绝对路径”) - 避免冗余描述,比如
"""This function adds two numbers."""不如"""Add two numbers and return their sum."""直接 - 中文项目可用中文 docstring,但术语、参数名、返回值类型仍建议用英文(如
user_id: int)
工具支持:写完记得验证
用 help(func_name) 可即时查看效果;配合 pydoc 命令生成模块文档。团队中可接入 pylint 或 pydocstyle 检查 docstring 是否缺失或格式错误。主流 IDE(如 PyCharm、VS Code)也支持基于 docstring 的参数提示和自动补全。










