如何修复Mypy报错:返回值类型不兼容(got "signedinteger[Any]", expected "int")
解决Mypy类型不兼容报错:numpy整数与原生int不匹配
错误原因
Mypy提示的类型不兼容问题,是因为np.argmax()返回的是numpy的signedinteger[Any]类型(比如np.int64),而函数声明的返回值是Python原生int,两者在类型系统中被判定为不兼容。
修改方案
方案1:显式转换为原生int(推荐)
直接将numpy整数转换为Python原生int,从根本上统一类型:
import numpy as np import numpy.typing as npt def first_true_pos(x: npt.NDArray) -> int: """ for logical ndarray x, returns the index of the first True value if any, otherwise -1 """ if len(x) < 1: return -1 i = np.argmax(x) if x[i]: return int(i) # 转换为Python原生int return -1
方案2:强制标注变量类型
通过类型标注告诉Mypy,np.argmax()的结果可以被视为原生int:
import numpy as np import numpy.typing as npt def first_true_pos(x: npt.NDArray) -> int: """ for logical ndarray x, returns the index of the first True value if any, otherwise -1 """ if len(x) < 1: return -1 i: int = np.argmax(x) # 强制指定变量类型为int if x[i]: return i return -1
方案3:使用类型断言
通过typing.cast明确向Mypy断言类型兼容性:
import numpy as np import numpy.typing as npt from typing import cast def first_true_pos(x: npt.NDArray) -> int: """ for logical ndarray x, returns the index of the first True value if any, otherwise -1 """ if len(x) < 1: return -1 i = np.argmax(x) if x[i]: return cast(int, i) # 类型断言 return -1
方案说明
- 方案1是最稳妥的选择,它在运行时实际执行类型转换,避免潜在的类型相关问题;
- 方案2和3仅在类型检查层面生效,不会改变运行时的变量类型,适合确定numpy整数可以安全转换为原生int的场景。
内容的提问来源于stack exchange,提问作者Fortranner
相关产品推荐
相关产品推荐

