我被困在试图理解TypeVar
以两种不同方式使用它时的边界:
Enums = TypeVar("Enums", Enum1, Enum2)
Enums = TypeVar("Enums", bound=Union[Enum1, Enum2])
这是我正在使用的代码:
#!/usr/bin/env python3.6
"""Figuring out why enum is saying incompatible return type."""
from enum import IntEnum, EnumMeta
from typing import TypeVar, Union
class Enum1(IntEnum):
MEMBER1 = 1
MEMBER2 = 2
class Enum2(IntEnum):
MEMBER3 = 3
MEMBER4 = 4
# Enums = TypeVar("Enums", bound=Union[Enum1, Enum2]) # Case 1... Success
Enums = TypeVar("Enums", Enum1, Enum2) # Case 2... error: Incompatible return value
def _enum_to_num(val: int, cast_enum: EnumMeta) -> Enums:
return cast_enum(val)
def get_some_enum(val: int) -> Enum1:
return _enum_to_num(val, Enum1)
def get_another_enum(val: int) -> Enum2:
return _enum_to_num(val, Enum2) # line 35
运行时mypy==0.770
:
Case 1
:Success: no issues found
Case 2
:35: error: Incompatible return value type (got "Enum1", expected "Enum2")
这种情况与这个问题非常相似:Difference between TypeVar('T', A, B) and TypeVar('T', bound=Union[A, B])
答案解释了使用案例 1( bound=Union[Enum1, Enum2]
) 时,以下是合法的:
Union[Enum1, Enum2]
Enum1
Enum2
并且在使用案例 2 ( A, B
) 时,以下是合法的:
Enum1
Enum2
但是,我认为这个答案不能解释我的问题,我没有使用这种Union
情况。
谁能告诉我发生了什么事?
慕虎7371278
aluckdog
相关分类