python 如何键入使用默认值动态创建的枚举?

dojqjjoe  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(154)

使用FunctionalAPI,我想输入我的枚举,这样它就会有一个默认的已知值。
示例:

class MyBaseClass:
    ...

class DerivedA(MyBaseClass):
    ...

class DerivedB(MyBaseClass):
    ...

DerivedChoice = enum.Enum('DerivedChoice', {cls.__name__: cls for cls in (DerivedA, DerivedB)})

foo: DerivedChoice = DerivedChoice.DerivedB

foo.value  # <- this should be  `MyBaseClass`
s3fp2yjn

s3fp2yjn1#

这里有一个不错的解决方案

T = TypeVar('T')

if TYPE_CHECKING:
    class DefaultEnum(Generic[T], enum.Enum):  # this class does not exist at runtime
        @property
        def value(self) -> T:
            ...

def default_enum(name: str, members: dict[str, T], type: T) -> 'DefaultEnum[T]':
    return enum.Enum(name, members)  # type: ignore

用法:

class MyBase:
    foo: int
    bar: str

class A(MyBase):
    ...

class B(MyBase):
    ...

MyBaseDerived = default_enum(name='MyBaseDerived',
                             members={cls.__name__: cls for cls in (A, B)},
                             type=MyBase)

MyBaseDerived.value.foo  # <- hinted by PyCharm
    • 编辑:**

这一个似乎在VSCode上工作

from typing import Generic, TypeVar, TYPE_CHECKING
import enum

T = TypeVar('T')

if TYPE_CHECKING:
    from dataclasses import dataclass

    class EnumProperty(Generic[T]):
        name: str
        value: T

    class DefaultEnum(Generic[T]):  # this class does not exist at runtime
        def __getattribute__(self, item) -> 'EnumProperty[T]':
            ...

def default_enum(name: str, members: dict[str, T], type: T) -> 'DefaultEnum[T]':
    return enum.Enum(name, members)  # type: ignore

相关问题