微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在嵌套数据结构中时,mypy 未检测到泛型类型不匹配

如何解决在嵌套数据结构中时,mypy 未检测到泛型类型不匹配

我遇到过这样一种情况,在嵌套结构中使用泛型时,mypy 似乎无法检测到类型不匹配。

T = TypeVar('T')


class Constructable(ABC,Generic[T]):

    def __init__(self,parameter: T):
        pass


class ConstructableWithInt(Constructable[int]):
    pass


class TypeContainer(Generic[T]):
    constructable: Type[Constructable[T]]

    def __init__(
            self,constructable: Type[Constructable[T]]
    ):
        self.constructable = constructable


class ConstructionTuple(Generic[T]):
    constructable: TypeContainer[T]
    parameter: T

    def __init__(self,spec: TypeContainer[T],parameter: T):
        self.spec = spec
        self.parameter = parameter


class ConstructableTupleWrapper(Generic[T]):
    constructable_tuple: ConstructionTuple[T]

    def __init__(self,constructable_tuple: ConstructionTuple[T]):
        self.constructable_tuple = constructable_tuple


constructable_with_int_wrapper = TypeContainer(
    constructable=ConstructableWithInt,)

# this leads to an error in mypy due to mismatch of `str` and `int`
mismatching_int_and_string_directly = ConstructionTuple(
    spec=constructable_with_int_wrapper,parameter="5"
)

mismatching_int_and_string_within_wrapper = ConstructableTupleWrapper(
    # this produces no error,even though it has the same mismatch
    constructable_tuple=ConstructionTuple(
        spec=constructable_with_int_wrapper,parameter="5"
    )
)

我是否使用了泛型错误,或者这可能是 [python generics / mypy] 中的一个错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。