在开源贡献中撰写符合规范的 docstring 示例
解读
面试官抛出此题,并非让你背一段“标准答案”,而是验证三件事:
- 你是否真的读过 scikit-learn 源码(尤其是
sklearn/base.py与maint_tools里的模板); - 你是否理解 numpydoc 风格 与 Sphinx-Gallery 自动化测试 的耦合关系;
- 你能否在 中文开源社区 的 PR 评审语境下,把“写注释”升级为“写可维护的公共契约”。
答得太短会被认为“没贡献过”,答得冗长又会被吐槽“过度设计”。因此,要给出一个 能直接粘进 PR 里、一次通过 CI 的最小合规示例,并解释每一行的“潜规则”。
知识点
- numpydoc 标准:scikit-learn 强制使用 numpydoc,拒绝 Google/Rest 风格;字段顺序、空行、冒号后空格全部有正则检查。
- Estimator 契约:所有实现必须带
Attributes与See Also段落;Parameters里禁止出现self。 - doctest 语法:示例代码必须能被
pytest sklearn/xxx/tests/test_docstring.py::test_docstring一次性捕获;浮点输出需写...做模糊匹配。 - 中文社区潜规则:PR 标题必须带
[DOC],docstring 里禁止出现中文标点;示例数据用load_iris等内置集,避免外网下载。 - 交叉引用:引用同类 Estimator 时必须用
:class:sklearn.xxx.Xxx`` 格式,否则 Sphinx 会报警告。
答案
以下示例直接取自 2023 年并入主线的 sklearn.linear_model._ridge.Ridge 简化版,可无缝通过 maint_tools/test_docstring.py:
class Ridge(LinearModel):
"""
Linear least squares with l2 regularization.
Minimizes the objective function: ||y - Xw||^2_2 + alpha * ||w||^2_2
This estimator has built-in support for sparse matrices and
automatic cross-validation.
Parameters
----------
alpha : float, default=1.0
Regularization strength; must be a positive float. Larger values
specify stronger regularization.
fit_intercept : bool, default=True
Whether to calculate the intercept for this model. If set to False,
no intercept will be used in calculations (i.e., data is expected to
be centered).
copy_X : bool, default=True
If True, X will be copied; else, it may be overwritten.
Attributes
----------
coef_ : ndarray of shape (n_features,) or (n_targets, n_features)
Weight vector(s).
intercept_ : float or ndarray of shape (n_targets,)
Independent term in decision function.
n_features_in_ : int
Number of features seen during :meth:`fit`.
See Also
--------
RidgeCV : Ridge regression with built-in cross-validation.
Lasso : Linear Model trained with L1 prior as regularizer.
Examples
--------
>>> from sklearn.datasets import load_diabetes
>>> from sklearn.linear_model import Ridge
>>> X, y = load_diabetes(return_X_y=True)
>>> clf = Ridge(alpha=0.1)
>>> clf.fit(X, y)
Ridge(alpha=0.1)
>>> clf.predict(X[:2])
array([151.495..., 75.771...])
"""
关键检查点
- 冒号后必须留一个空格,
default=1.0与描述之间留两个空格,否则numpydoc正则报错。 - 示例输出用
...忽略浮点精度,确保 32/64 位系统均通过。 See Also里只写同类 Estimator,禁止写函数或第三方库。
拓展思考
- CI 红线:从 1.3 版开始,scikit-learn 在
.github/workflows/lint.yml里新增numpydoc-validation,一旦 docstring 出现Parameters与__init__签名不一致,PR 会被机器人直接关闭;本地可用python maint_tools/test_docstring.py sklearn.linear_model.Ridge预检。 - 中文注释争议:国内贡献者常在代码里写中文 TODO,但 docstring 绝对禁止;若想给中文用户写科普,应另开
examples/zh_cn/目录,按 Sphinx-Gallery 规范提交.py文件,而非改 docstring。 - 性能陷阱:示例数据若用
np.random.rand,每次文档构建结果不同,会导致 doctest 失败;正确做法是sklearn.datasets.make_regression(n_samples=10, random_state=0),用固定随机种子。 - 进阶加分:如果你能在 PR 描述里贴出
python -m numpydoc sklearn.linear_model.Ridge的 0-warning 截图, maintainer 会优先合并——这是国内开源圈公认的“ professionalism 信号”。