You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用mypy确保函数接收的是NumPy浮点数组参数?

mypy检查NumPy浮点数组参数的实现方法

mypy完全可以检查函数参数是否为NumPy浮点数组,你当前的问题出在类型标注和mypy配置上,以下是解决步骤:

1. 确保依赖版本正确

先升级numpy和对应的类型存根,避免旧版本的类型支持不全:

pip install numpy numpy-stubs --upgrade

2. 修正函数类型标注

你之前用的np.cfloat是复数浮点类型,整数/布尔数组可隐式转换为复数数组,所以mypy没报错。如果要限制为普通浮点数组,需要用np.floating(适配任意浮点类型)或具体的浮点类型(如np.float64):

接受任意浮点类型数组的写法

import numpy as np
import numpy.typing as npt
from typing import Any

def half(x: npt.NDArray[np.floating[Any]]):
    return x/2

print(half(np.full(4,2.1)))  # 合法:float64类型数组
print(half(np.full(4,6)))    # mypy会报错:类型不兼容,期望浮点数组,传入整数数组
print(half(np.full(4,True))) # mypy会报错:类型不兼容,期望浮点数组,传入布尔数组

只接受特定浮点类型的写法

如果要严格限制为float64类型:

def half(x: npt.NDArray[np.float64]):
    return x/2

3. 开启mypy的numpy严格检查

运行mypy时需要启用--strict-numpy选项,或者在mypy.ini/pyproject.toml中配置:

mypy --strict-numpy your_script.py

配置文件示例(pyproject.toml):

[tool.mypy]
strict_numpy = true

这样配置后,mypy就会对传入整数、布尔类型的NumPy数组抛出类型错误。

内容的提问来源于stack exchange,提问作者Fortranner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:18:31