from typing import TypeVar, Type, Generic, Callable
class BaseModel(_BaseModel):
pass
T = TypeVar('T')
GT = TypeVar('GT')
# 扩展 enum
class EnumBase(Generic[GT], _Enum):
# 额外对象
extra_obj: GT
def __new__(
cls: Type[T], value: str, extra_obj: GT = None,
) -> T:
obj = object.__new__(cls)
obj._value_ = value
obj.extra_obj = extra_obj
return obj
class B:
def __init__(self, value):
self.value = value
# 这里应该如何注释泛型? 这样写 pycharm 是会提示类型的, 但是会报错
class EnumTest(EnumBase[B]):
A = 'A', B(1)
B = 'B', B(2)
foo = EnumTest.A.extra_obj
print(foo.value)
报错内容是
File "xxx", line 35, in
class EnumTest(EnumBase[B]):
File "xxx\enum.py", line 408, in __getitem__
return cls._member_map_[name]
KeyError:
也就是说 EnumBase[B]会直接触发 EnumMeta 的__getitem__, 不知道有没有什么好的解决办法