pydantic设置带注释类型的默认值

发布于 2025-01-31 15:27:49 字数 798 浏览 3 评论 0原文

因此,我一直在尝试使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最初的梦 2025-02-07 15:27:49

我正在使用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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文