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

