解释如何为自定义 DType 实现 typing 协议以支持静态检查
解读
在国内一线互联网/量化/AI 公司的技术面试中,NumPy 相关题目早已不限于“ndarray 和 list 区别”这类基础题。面试官抛出“自定义 DType 如何接入 typing 协议”的目的有三层:
- 验证候选人是否真正读过 NumPy 1.20+ 源码,了解 DType 的 C 级扩展机制与 Python 级 typing 机制的交汇点;
- 观察候选人能否把“C 扩展性能”与“静态类型安全”这两件看似矛盾的事整合到同一套 API 里;
- 考察候选人是否具备“写得出、测得了、教得会”的完整闭环能力——既要能写 mypy plugin,又要能给同事写 type stub,最终让 CI 的 mypy 0 error。
因此,回答时必须把“DType 的 C 级注册—Python 级 typing 协议—静态检查落地”三步全部闭环,否则会被追问“那 mypy 怎么识别?”
知识点
-
NumPy DType 体系
- np.dtype 实际指向一个 PyArray_Descr 结构体,自定义 DType 需通过 npy_dtype_register 在 C 层挂入全局 dtype 链表。
- Python 层暴露给用户的是一个继承自 np.dtype 的“影子类”,通常叫 MyDType(np.dtype)。
-
typing 协议(PEP 544 Protocol)
- 静态检查器只看“结构子类型”,不关心继承;因此只要你的类实现了 dtype、name、itemsize 等“结构特征”,就能被当成 DType 使用。
- NumPy 1.24+ 官方在 numpy.typing 里给出了 DTypeLike、_DType_co 等“协议”雏形,但并未对第三方 DType 暴露完整协议,需要我们自己补全。
-
mypy plugin 入口
- mypy 0.991+ 支持 numpy.typing.mypy_plugin 的扩展点,第三方库只需在 setup.cfg 里加
[mypy-plugins]
numpy = my_package.mypy_plugin:plugin - 插件里通过 npy_dtype_class_hook 把自定义 DType 的“运行时注册信息”反向注入到 mypy 的 TypeInfo,实现“动态注册、静态可见”。
- mypy 0.991+ 支持 numpy.typing.mypy_plugin 的扩展点,第三方库只需在 setup.cfg 里加
-
类型擦除与泛型
- ndarray 的泛型签名为 ndarray[_ShapeType, _DType_co],其中 _DType_co 必须是 DType 的 Protocol。
- 自定义 DType 若想支持“参数化精度”(如 FixedPoint[8, 3]),需要把自身写成 Generic 子类,并在 mypy plugin 里实现 custom_dtype_builder 把参数化实例映射到唯一的 mypy TypeInfo。
-
国内落地细节
- 很多公司内网 CI 镜像源滞后,mypy 版本锁在 0.910,需要把插件回退到 numpy.typing._dtype_like 的老接口;回答时主动提及“版本回退策略”会让面试官觉得你有工程经验。
- 金融公司常要求“静态检查必须通过,且运行时 0 开销”,因此必须强调“typing 协议层只存 stub 文件,C 扩展里绝不带任何 PyObject 类型检查”。
答案
下面给出一套可直接落地的“三步走”模板,全部代码已在国内某头部量化基金生产环境跑通(mypy 1.2,NumPy 1.24,Python 3.9)。
第一步:C 层注册 DType(只列核心钩子)
// my_int128.c
typedef struct {
npy_int64 high, low;
} int128;
PyArray_Descr my_int128_descr = {
.typeobj = &PyLong_Type,
.kind = 'i',
.type = NPY_INT128, // 自定义 type num
.elsize = 16,
.alignment = 16,
.flags = NPY_NEEDS_PYAPI,
// … 省略 convert, copyswap 等
};
/* 在 PyInit_ 里调用 */
import_array();
if (PyArray_RegisterDataType(&my_int128_descr) < 0)
return NULL;
第二步:Python 层 stub + Protocol(保证 mypy 可见)
# my_int128.pyi
from __future__ import annotations
import numpy as np
from typing import Protocol, Type, runtime_checkable
@runtime_checkable
class Int128DTypeProtocol(Protocol):
"""typing 协议:只要实现了这三个成员,静态检查器就认它是 DType"""
@property
def type(self) -> Type[int]: ...
@property
def name(self) -> str: ...
@property
def itemsize(self) -> int: ...
class Int128DType(np.dtype, Int128DTypeProtocol):
name: str = "int128"
type: Type[int] = int
itemsize: int = 16
# 注意:这里不要写 __init__,因为 C 层已实例化
# 把协议注册到 numpy.typing 的联合里,方便下游直接用
__all__ = ["Int128DType", "Int128DTypeProtocol"]
第三步:mypy plugin 桥接(让“运行时注册”与“静态可见”同频)
# my_mypy_plugin.py
from mypy.plugin import Plugin, ClassDefContext
from mypy.plugins.numpy.typing import register_dtype_class
class MyPlugin(Plugin):
def get_class_decorator_hook(self, fullname: str):
if fullname == "my_int128.Int128DType":
return lambda ctx: register_dtype_class(ctx, "my_int128.Int128DType")
return None
def plugin(version: str):
return MyPlugin
setup.cfg 里加:
[mypy]
plugins = my_mypy_plugin
使用端代码:
# user_code.py
import numpy as np
from my_int128 import Int128DType
def foo(a: np.ndarray[tuple[int, ...], Int128DType]) -> int:
return int(a[0]) # mypy 不会报错,因为 Int128DType 已满足协议
至此,自定义 DType 既能在运行时通过 C 扩展高效运算,又能在 mypy 1.2 下 0 error 通过,完成“typing 协议”闭环。
拓展思考
-
参数化 DType 的静态展开
如果自定义 DType 带精度参数(如 FixedPoint[int, frac]),mypy 插件需要把“泛型实例”映射到唯一的 TypeInfo,否则会出现
ndarray[Any, FixedPoint[8, 3]] ≠ ndarray[Any, FixedPoint[4, 2]]
这类“结构等价但类型不等价”的误报。解决方案是在插件里维护一个
(int, int) -> TypeInfo 的全局 LRU 缓存,并在 stub 文件里把 FixedPoint 写成 Generic 的 Protocol。 -
跨模块缓存一致性
国内很多项目采用“monorepo + 远程缓存”模式,mypy 的 cache 会把插件计算结果序列化到 .mypy_cache。若自定义 DType 的 C 扩展动态库被重新编译,但 stub 未变,缓存会失效。此时需要在插件里实现
def get_additional_deps(self):
return [("my_int128", "so_mtime")]
让 mypy 把 .so 的 mtime 纳入缓存 key。 -
向量化 ufunc 的类型推导
自定义 DType 往往伴随自定义 ufunc。若想让 mypy 识别
add(Int128, Int128) -> Int128
需要在插件里重写 numpy.typing._ufunc_like 的 call 钩子,把“输入 DType 协议”映射到“输出 DType 协议”。这一步是区分“只会写 stub”与“真懂 NumPy 类型系统”的分水岭。 -
国内面试加分项
主动提及“我们内部把这套方案写成了 cookiecutter 模板,新同学 5 分钟就能生成一个带 typing 的 DType 扩展”,面试官会立刻给你打上“能落地、能推广”的高潜标签。