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

为何mypy允许list[str | int]与list[int]相加却报错返回该结果?

问题原因解析

这是mypy的上下文类型检查规则和Python列表类型特性共同导致的:

  • mypy对列表+操作的类型约束很严格:列表的__add__方法要求两个操作数必须是元素类型完全一致的列表。由于Python的list是不变类型,list[int]并不属于list[str | int]的子类型,所以从严格类型规则来看,list[str | int] + list[int]本身是不符合规范的。
  • 当l1 + l2作为单独语句存在时,mypy没有强制验证表达式的类型合法性(因为没有后续的类型约束,比如赋值或返回),所以不会报错;但当你把它作为返回值时,mypy必须验证结果类型是否匹配函数的返回类型list[str | int],这时候会严格执行类型检查,发现操作数类型不兼容,因此抛出错误。

解决方法

如果你需要保留这个逻辑,可以通过以下方式让mypy认可:

  • 显式将l2转换为list[str | int]类型:
    def test() -> list[str | int]:
        l1: list[str | int] = []
        l2: list[int] = []
        return l1 + list[str | int](l2)
    
  • 或者使用typing.cast告知mypy类型的兼容性:
    from typing import cast
    
    def test() -> list[str | int]:
        l1: list[str | int] = []
        l2: list[int] = []
        return l1 + cast(list[str | int], l2)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:13:15