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

Python函数泛型类型丢失引发mypy赋值类型不兼容错误

Python函数泛型类型丢失引发mypy赋值类型不兼容错误

我最近碰到了一个mypy类型检查报错,具体是赋值时提示类型不兼容,错误信息如下:

error: Incompatible types in assignment (expression has type "object", variable has type "A | B")  [assignment]

对应的代码示例是这样的:

from dataclasses import dataclass
from typing import TypeVar, Mapping, reveal_type


@dataclass
class A:
    foo: str = "a"

@dataclass
class B:
    bar: str = "b"

lookup_table: Mapping[str, type[A] | type[B]] = {
    "a": A,
    "b": B
}

reveal_type(lookup_table)  # note: Revealed type is "typing.Mapping[builtins.str, Union[type[simple.A], type[simple.B]]]"
T = TypeVar("T")

def load(lookup_table: Mapping[str, type[T]], lookup_key:str) -> T:
    con: type[T] = lookup_table[lookup_key]
    instance: T = con()
    return instance

example_a: A | B = load(lookup_table, "a")  # error: Incompatible types in assignment (expression has type "object", variable has type "A | B")
print(example_a)

补充说明:我已经将这个问题记录为mypy的bug了。

备注:内容来源于stack exchange,提问作者sixtyfootersdude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:24:28