当输入和输出中有多种类型但它们之间具有一对一关系时的类型提示
我有以下代码:
AnyTypeEnum = TypeVar("AnyTypeEnum", Type[Enum], Type[IntEnum])
AnyEnum = TypeVar("AnyEnum", Enum, IntEnum)
def decode(value: str, enum_class: AnyTypeEnum) -> AnyEnum:
return make_map(enum_class)[value]
@functools.cache()
def make_map(enum_class: AnyTypeEnum) -> Dict[str, AnyEnum]:
return {x.name: x for x in enum_class}
如果我传递 IntEnum 类,我将在输出中包含 IntEnum 值,与 Enum 相同。从一个阶级到另一个阶级的价值观的混合是不可能的。
然而,mypy 报告错误:
1.第 9 行:字典理解具有不兼容的类型 Enum,预期的 IntEnum
2.第 9 行:字典理解具有不兼容的类型 IntEnum,预期的枚举
我正在使用 TypeVar 来解决之间的“类型混合”问题如果我使用 Union 代替,则会出现输入和输出,但显然它还没有完全修复。
我该如何解决这个问题?
I have the following code:
AnyTypeEnum = TypeVar("AnyTypeEnum", Type[Enum], Type[IntEnum])
AnyEnum = TypeVar("AnyEnum", Enum, IntEnum)
def decode(value: str, enum_class: AnyTypeEnum) -> AnyEnum:
return make_map(enum_class)[value]
@functools.cache()
def make_map(enum_class: AnyTypeEnum) -> Dict[str, AnyEnum]:
return {x.name: x for x in enum_class}
If I pass an IntEnum class, I'll have in output IntEnum values, same with Enum. The mix from a class to the values of the other one is never possible.
Yet, mypy reports the erros:
1.Line 9: dictionary comprehension has incompatible type Enum, expected IntEnum
2.Line 9: dictionary comprehension has incompatible type IntEnum, expected Enum
I'm using TypeVar to solve the problem of "type mixing" between input and output that is present if I use Union instead, but apparently it's not completely fixed.
How do I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有任何约束力的输出和输入类型。目前,它们完全无关。 或者尝试一下
,
@Overload
应该有效。You have nothing binding your output and input types. At the moment they're entirely unrelated. Try this
Alternatively,
@overload
should work.