从字符串数组初始化pydantic Literal



我想从字符串数组中初始化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仅允许一个或多个文字boolintstrbytesenum值、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

相关内容

  • 没有找到相关文章

最新更新