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

Python/mypy元组穷尽性检查匹配报错问题咨询

Union类型模式匹配的mypy穷尽性检查问题

尝试对tuple[int, float] | str类型的变量执行模式匹配,以让mypy完成穷尽性检查,使用的代码如下:

t: tuple[int, float] | str
match t:
    case str():
        print("found str")
    case (int(), float()):
        print("found tuple")
    case _ as unreachable:
        assert_never(unreachable)

认为已覆盖所有分支,但收到mypy错误提示:

Argument 1 to "assert_never" has incompatible type "tuple[<nothing>, <nothing>]"; expected "NoReturn"  [arg-type]

问题原因与解决方法

这不是mypy的bug,是元组模式匹配的写法错误。case (int(), float())属于值匹配,它会检查元组元素是否是int()(即字面量0)和float()(即字面量0.0)的实例,而非匹配tuple[int, float]类型。

要正确匹配tuple[int, float]类型,需使用类型模式匹配,有两种写法:

  • 需要绑定变量时:case (int() as x, float() as y):
  • 无需绑定变量时:case (int, float):

修改后的完整代码:

from typing import assert_never

t: tuple[int, float] | str
match t:
    case str():
        print("found str")
    case (int, float):
        print("found tuple")
    case _ as unreachable:
        assert_never(unreachable)

此时mypy会正确识别所有分支已被覆盖,通过穷尽性检查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 11:42:33