gpt4 book ai didi

python - 从字符串数组初始化pydantic Literal

转载 作者:行者123 更新时间:2023-12-04 15:08:14 31 4
gpt4 key购买 nike

我想从字符串数组中初始化一个 pydantic 文字

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]
但我强烈建议不要使用这种语法,而是坚持使用 canonical一,这也是类型检查器允许的:
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

关于python - 从字符串数组初始化pydantic Literal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65675648/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com