我想从字符串数组中初始化pydantic Literal
from typing import Literal
from pydantic import BaseModel
CLASS_NAME_VALUES = ["primary", "secondary", "success", "danger", "warning", "info", "dark"]
ICON_NAME_VALUES = ["electricity.svg", "water.svg",
"internet.svg", "naturalGas.svg", "noCategory.svg"]
class CategoryRequest(BaseModel):
class_name: Literal[CLASS_NAME_VALUES]
icon_name: Literal[ICON_NAME_VALUES]
但我得到以下错误
File "pydantic/main.py", line 252, in pydantic.main.ModelMetaclass.__new__
File "pydantic/fields.py", line 309, in pydantic.fields.ModelField.infer
File "pydantic/fields.py", line 271, in pydantic.fields.ModelField.__init__
File "pydantic/fields.py", line 351, in pydantic.fields.ModelField.prepare
File "pydantic/fields.py", line 529, in pydantic.fields.ModelField.populate_validators
File "pydantic/validators.py", line 566, in find_validators
File "pydantic/validators.py", line 410, in pydantic.validators.make_literal_validator
TypeError: unhashable type: 'list'
有什么建议吗?
在运行时,允许将任意值作为Literal[...]
的类型参数,但类型检查器可能会施加限制。例如,mypy
仅允许一个或多个文字bool
、int
、str
、bytes
、enum
值、None
和其他Literal
类型的别名。例如,不允许使用Literal[3 + 4]
或List[(3, 4)]
。
至于pydantic
,它允许在Literal
中使用可散列类型的值,如tuple
。例如,您的样本可以使用tuple
重写为:
from typing import Literal
from pydantic import BaseModel
CLASS_NAME_VALUES = ("primary", "secondary", "success", "danger", "warning", "info", "dark")
ICON_NAME_VALUES = ("electricity.svg", "water.svg",
"internet.svg", "naturalGas.svg", "noCategory.svg")
class CategoryRequest(BaseModel):
class_name: Literal[CLASS_NAME_VALUES]
icon_name: Literal[ICON_NAME_VALUES]
但我强烈建议不要使用这种语法,而是坚持使用规范语法,这也是类型检查器允许的:
CLASS_NAME_VALUES = Literal["primary", "secondary", "success", "danger", "warning", "info", "dark"]
ICON_NAME_VALUES = Literal["electricity.svg", "water.svg",
"internet.svg", "naturalGas.svg", "noCategory.svg"]
class CategoryRequest(BaseModel):
class_name: CLASS_NAME_VALUES
icon_name: ICON_NAME_VALUES