枚举的Python类型提示名称

问题描述 投票:0回答:1

在 Python 中,如何输入提示变量以将其限制为枚举中的名称?

class DataFormatOptions(Enum):
    calibrate = "Calibrate"
    lrs = "LRS"
    custom = "Custom"


_E = TypeVar("_E", bound=DataFormatOptions)


class DataFormat(BaseModel):
    name: Type[_E]  # <- How do type hint this? It should be either "calibrate", "lrs" or "custom"
    displayName: DataFormatOptions

我想重用枚举中的名称,而不是仅仅在文字中复制,例如

name: Literal["calibrate", "lrs", "custom"]
python mypy python-typing
1个回答
0
投票

我明白你想要实现什么,但是

Literal
无法动态设置:

from enum import Enum
from pydantic import BaseModel
from typing import TypeVar, Literal

# ...

names = tuple([member.name for member in DataFormatOptions])

class DataFormat(BaseModel):
    name: Literal[names] # <-- Pylance squiggles here on "names"
    displayName: DataFormatOptions

皮兰斯错误:

Type arguments for "Literal" must be None, a literal value (int, bool, str, or bytes), or an enum value (Pylance)

(variable) names: tuple[str, ...]
© www.soinside.com 2019 - 2024. All rights reserved.