当输入和输出中有多种类型但它们之间具有一对一关系时的类型提示

发布于 2025-01-18 21:46:59 字数 663 浏览 3 评论 0原文

我有以下代码:

 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小矜持 2025-01-25 21:46:59

您没有任何约束力的输出和输入类型。目前,它们完全无关。 或者尝试一下

AnyEnum = TypeVar("AnyEnum", Enum, IntEnum)

def decode(value: str, enum_class: Type[AnyEnum]) -> AnyEnum:
    return make_map(enum_class)[value]

@functools.cache()
def make_map(enum_class: Type[AnyEnum]) -> Dict[str, AnyEnum]:
    return {x.name: x for x in enum_class}

@Overload应该有效。

You have nothing binding your output and input types. At the moment they're entirely unrelated. Try this

AnyEnum = TypeVar("AnyEnum", Enum, IntEnum)

def decode(value: str, enum_class: Type[AnyEnum]) -> AnyEnum:
    return make_map(enum_class)[value]

@functools.cache()
def make_map(enum_class: Type[AnyEnum]) -> Dict[str, AnyEnum]:
    return {x.name: x for x in enum_class}

Alternatively, @overload should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文