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

遍历参数列表时遇到mypy类型提示兼容问题

问题分析与解决

问题描述

以下代码运行正常,但mypy会抛出类型错误:

def test(a: int | tuple[int, int]):
    print(a)


if __name__ == "__main__":
    for b in [1, (1, 2)]:
        test(b)

mypy输出错误:

7: error: Argument 1 to "test" has incompatible type "object"; expected "Union[int, Tuple[int, int]]"  [arg-type]

使用环境:

platform win32 -- Python 3.11.1, pytest-7.2.0, pluggy-1.0.0
plugins: anyio-3.6.2, mypy-0.10.3

原因

mypy默认会把包含不同类型元素的列表推断为list[object]——因为Python列表是同质容器,mypy无法确定你后续是否会往列表中添加其他类型的元素,所以会选择最宽泛的父类型object。循环变量b的类型因此被推断为object,和test函数要求的int | tuple[int, int]类型不兼容。

解决方案

显式标注列表的类型,让mypy明确知道列表元素的允许类型:

def test(a: int | tuple[int, int]):
    print(a)


if __name__ == "__main__":
    # 显式指定列表元素类型为int或二元int元组
    items: list[int | tuple[int, int]] = [1, (1, 2)]
    for b in items:
        test(b)

这样mypy就能正确推断b的类型为int | tuple[int, int],与test的参数类型匹配,错误会消失。

内容的提问来源于stack exchange,提问作者FluidMechanics Potential Flows

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 06:15:38