用 numpydoc 格式为自定义 ufunc 编写文档并生成 Sphinx HTML

解读

国内一线互联网/量化/AI 公司的 NumPy 岗位面试,常把“写文档”当成“硬门槛”:

  1. 代码必须能跑,2. 文档必须能自动生成,3. 生成的 HTML 要能在 CI 里一键发布。
    本题把“自定义 ufunc”与“numpydoc + Sphinx”绑在一起,考察三点:
  • 是否真正理解 ufunc 的 C 级注册机制(PyUFunc_FromFuncAndData)
  • 能否用 numpydoc 规范(不是随便写 docstring)把数学语义、类型、异常、示例全部覆盖
  • 能否把 Sphinx 配置到“开箱即用”——包括 autodoc、autosummary、napoleon、intersphinx、mathjax 一个不落,且能正确解析 C 扩展模块。

面试官通常会在 30 min 内让你现场演示:

  • python setup.py build_ext --inplace 通过
  • make html 无 warning
  • 打开 _build/html/generated/your.ufunc.html 能看到 Parameters、Returns、Notes、Examples 四栏,且 Examples 里的代码块能直接复制运行。

任何一步报错,直接视为“基础不牢”。

知识点

  1. ufunc 的两种实现路径
    a. 纯 Python: np.frompyfunc —— 慢,只能做教学演示
    b. C 扩展: PyUFunc_FromFuncAndData —— 真·生产级,需写 loops.c、类型签名、dtype cast table
  2. numpydoc 字段规范
    必须出现的段落:Summary、Parameters、Returns、Raises、See Also、Notes、Examples
    每个参数需有 {type, shape, description} 三元组;shape 用 (M, N) 记法
    Examples 里必须含 >>> 可执行代码,且运行结果与 docstring 一致(doctest 风格)
  3. Sphinx 关键配置
    extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon', 'numpydoc', 'sphinx.ext.intersphinx']
    numpydoc_show_class_members = False 避免重复
    intersphinx_mapping = {'numpy': ('https://docs.scipy.org/doc/numpy/', None)} 保证 :func:numpy.add`` 能跳转
  4. 中文工程化细节
    源码采用 UTF-8 无 BOM;Sphinx 主 conf.py 加 language = 'zh_CN';html_theme = 'pydata_sphinx_theme' 已通过工信部开源镜像站备案,国内下载快
  5. CI 钩子
    在 .gitlab-ci.yml 或 GitHub Actions 里加:
    script:
      - python -m pip install -e .
      - python -m sphinx -W -b html docs build/html
    
    -W 把 warning 当 error,面试官会重点看是否“零 warning”

答案

以下给出最小可运行示例,目录结构、C 源码、Python 包装、numpydoc 模板、Sphinx 配置一步不落,可直接 git clone 跑通。

目录结构

demo_ufunc/
├── setup.py
├── src/
│   ├── loops.c
│   └── __init__.py
├── docs/
│   ├── conf.py
│   ├── index.rst
│   └── _templates/
└── README.md
  1. C 循环核心 src/loops.c
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "Python.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/npy_3kcompat.h"

static void double_add(char **args, npy_intp *dimensions,
                       npy_intp *steps, void *data)
{
    npy_intp i;
    npy_intp n = dimensions[0];
    char *in1 = args[0], *in2 = args[1], *out = args[2];
    npy_intp step1 = steps[0], step2 = steps[1], step_out = steps[2];

    for (i = 0; i < n; i++) {
        *(double *)out = *(double *)in1 + *(double *)in2;
        in1 += step1;
        in2 += step2;
        out += step_out;
    }
}

/* 类型签名表 */
static PyUFuncGenericFunction add_funcs[] = { double_add };
static char add_types[] = { NPY_DOUBLE, NPY_DOUBLE, NPY_DOUBLE };
static void *add_data[] = { (void *)NULL };

/* Python 模块初始化 */
static struct PyMethodDef module_methods[] = {
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef moduledef = {
    PyModuleDef_HEAD_INIT,
    "demo_ufunc",
    NULL,
    -1,
    module_methods,
};

PyMODINIT_FUNC PyInit_demo_ufunc(void)
{
    PyObject *m = PyModule_Create(&moduledef);
    if (!m) return NULL;

    import_array();
    import_umath();

    PyObject *add = PyUFunc_FromFuncAndData(
        add_funcs, add_data, add_types,
        1,   /* nttypes */
        2,   /* nin     */
        1,   /* nout    */
        PyUFunc_None, /* identity */
        "add",        /* name      */
        "Add two arrays element-wise, using C speed.", /* doc */
        0              /* unused    */
    );
    if (!add) return NULL;
    PyModule_AddObject(m, "add", add);
    return m;
}
  1. Python 包装 src/init.py
from . import demo_ufunc
import numpy as np

add = demo_ufunc.add

# 用 numpydoc 写 docstring
add.__doc__ = """
Add two arrays element-wise with C-level performance.

Parameters
----------
x1 : array_like
    First input array.
x2 : array_like
    Second input array. Must be broadcastable to `x1`.

Returns
-------
add : ndarray
    The sum of `x1` and `x2`, element-wise.

Raises
------
TypeError
    If inputs cannot be cast to float64.

See Also
--------
numpy.add : NumPy's top-level ufunc doing the same operation.

Notes
-----
This ufunc is registered via ``PyUFunc_FromFuncAndData`` and
therefore supports all NumPy broadcasting rules out of the box.

Examples
--------
>>> from demo_ufunc import add
>>> import numpy as np
>>> a = np.array([1.0, 2.0, 3.0])
>>> b = np.array([4.0, 5.0, 6.0])
>>> add(a, b)
array([5., 7., 9.])
"""
  1. setup.py
from setuptools import setup, Extension
import numpy as np

ext = Extension(
    "demo_ufunc.demo_ufunc",
    sources=["src/loops.c"],
    include_dirs=[np.get_include()],
)

setup(
    name="demo_ufunc",
    version="0.1.0",
    packages=["demo_ufunc"],
    package_dir={"demo_ufunc": "src"},
    ext_modules=[ext],
    install_requires=["numpy>=1.19"],
)
  1. docs/conf.py
import os, sys
sys.path.insert(0, os.path.abspath('../src'))

project = 'demo_ufunc'
copyright = '2024, YourName'
author = 'YourName'
language = 'zh_CN'
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'numpydoc',
    'sphinx.ext.intersphinx',
    'sphinx.ext.mathjax',
]
numpydoc_show_class_members = False
intersphinx_mapping = {
    'numpy': ('https://docs.scipy.org/doc/numpy/', None),
}
html_theme = 'pydata_sphinx_theme'
  1. docs/index.rst
Welcome to demo_ufunc
=====================

.. automodule:: demo_ufunc
   :members:
   :undoc-members:
  1. 一键构建
$ python -m pip install -e .
$ cd docs
$ make html

打开 build/html/index.html 即可看到“add”函数完整文档,含 Parameters、Returns、Examples,且 Examples 代码块右上角有“Copy”按钮,符合国内阿里/腾讯/字节文档站点风格。

拓展思考

  1. 多类型支持
    目前只实现了 float64。生产环境需要把 add_types 扩展成 {NPY_INT32, NPY_INT32, NPY_INT32}、{NPY_FLOAT32, NPY_FLOAT32, NPY_FLOAT32} 等多组,并在 PyUFunc_FromFuncAndData 里把 ntypes 改成 3,否则面试官会追问“为什么只支持 double”。
  2. 向量化异常处理
    C 循环里如果可能出现 inf 或 nan,需要调用 np.seterr 的回调机制,或者把 PyUFunc_FromFuncAndData 的 identity 改成 PyUFunc_IdentityValue,并在 docstring 的 Notes 里写清异常行为,否则 doctest 会失败。
  3. 性能基准
    国内面试常要求现场跑 asv (airspeed velocity) 给出加速比。可写 benchmarks/bench_add.py,用 timeit 对比 numpy.add 与自定义 ufunc,确保差距 <5%,否则会被质疑“C 写了个 lonelier”。
  4. 中文搜索与 SEO
    Sphinx 生成 HTML 后,用 sphinx-sitemap 插件生成 sitemap.xml,再接入公司内网 Elasticsearch,实现中文检索。很多候选人只关注“能看”,却忽略“能搜”,在华为/百度等内部评审会被直接打回。
  5. 版本化文档
    用 sphinx-multiversion 把每次 tag 的文档都保留, interviewer 会随手点开 v0.1.0 与 v0.2.0 对比,确认你是否真的懂“文档即接口”。