pydantic设置带注释类型的默认值
因此,我一直在尝试使用Config JSON文件创建的Pydantic进行类。我一直在遇到一个试图设置默认值的问题。
基本思想是有一个步骤类型,可以用“类型”字段注释:
from typing import Literal, Union, List
from pydantic import Field
from typing_extensions import Annotated
import pydantic
import sys
class Type1Step(pydantic.BaseModel):
step_type: Literal["type_1"]
class Type2Step(pydantic.BaseModel):
step_type: Literal["type_2"]
StepT = Annotated[
Union[Type1Step, Type2Step],
Field(discriminator="step_type"),
]
class Plan(pydantic.BaseModel):
pre_steps: List[StepT] = ()
post_steps: List[StepT] = ()
但是我会得到此错误:
e valueerror:field
five 默认值无法在注释对于“ post_steps_0”,
我想我误解了带注释的类型的工作方式。有人对我做错了什么有任何想法吗?谢谢。
编辑:问题已解决。这是在Pydantic 1.9.1版中解决的错误。
So I've been trying to make a class using pydantic that is created through a config json file. I've been running into an issue where I am trying to set a default value.
The basic idea is that there is a step type, that can be annotated with a "type" field:
from typing import Literal, Union, List
from pydantic import Field
from typing_extensions import Annotated
import pydantic
import sys
class Type1Step(pydantic.BaseModel):
step_type: Literal["type_1"]
class Type2Step(pydantic.BaseModel):
step_type: Literal["type_2"]
StepT = Annotated[
Union[Type1Step, Type2Step],
Field(discriminator="step_type"),
]
class Plan(pydantic.BaseModel):
pre_steps: List[StepT] = ()
post_steps: List[StepT] = ()
but I get this error:
E ValueError: Field
default cannot be set in Annotated
for 'post_steps_0'
I think I am misunderstanding how the Annotated type works. Does anyone have any idea on what I am doing wrong? Thanks.
Edit: Issue has been solved. This was a bug solved in pydantic version 1.9.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我正在使用Pydantic版本1.9.0
这是一个错误,该错误已修复在Pydantic版本1.9.1:
https://github.com/samuelcolvin/pydantic/pull/4067
I was using pydantic version 1.9.0
This was a bug that was fixed in pydantic version 1.9.1:
https://github.com/samuelcolvin/pydantic/pull/4067