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
相关产品推荐
相关产品推荐

