pydantic:在将其分配到字段之前转换值?
我有以下模型
class Window(BaseModel):
size: tuple[int, int]
,我想这样实例化:
fields = {'size': '1920x1080'}
window = Window(**fields)
当然,这会失败,因为'size'
的值不是正确的类型。但是,我想添加逻辑,以便在x
上拆分该值,即:
def transform(raw: str) -> tuple[int, int]:
x, y = raw.split('x')
return int(x), int(y)
Pydantic支持这一点吗?
I have the following model
class Window(BaseModel):
size: tuple[int, int]
and I would like to instantiate it like this:
fields = {'size': '1920x1080'}
window = Window(**fields)
Of course this fails since the value of 'size'
is not of the correct type. However, I would like to add logic so that the value is split at x
, i.e.:
def transform(raw: str) -> tuple[int, int]:
x, y = raw.split('x')
return int(x), int(y)
Does Pydantic support this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
pydantic 2.x(编辑)
pydantic 2.0引入了
field_validator
装饰器,您可以以非常简单的方式实现这种行为。给定原始解析功能:注意:
cls
第一个参数所示。将其作为实例方法实现(使用self
)会引起错误。mode =“在”装饰器中的
在这里至关重要,正如预期的那样,这就是该方法在检查“大小”之前运行的方法。Pydantic 1.x(原始答案)
您可以使用Pydantic的
验证器
实现这种行为。给定预定义的函数:您可以在类中实现它:
注意传递给验证器的
pre = true
参数。这意味着它将在之前运行,默认验证器检查size
是一个元组。现在:
请注意,在那之后,您将无法用元组来实例化
窗口
。为了克服这一点,如果通过稍微更改代码通过元组,您可以简单地绕过该功能:
pydantic 2.x
pydantic 1.x 1.x
应该给出:
Pydantic 2.x (edit)
Pydantic 2.0 introduced the
field_validator
decorator which lets you implement such a behaviour in a very simple way. Given the original parsing function:Note:
cls
first argument. Implementing it as an instance method (withself
) will raise an error.mode="before"
in the decorator is critical here, as expected this is what makes the method run before checking "size" is a tuple.Pydantic 1.x (original answer)
You can implement such a behaviour with pydantic's
validator
. Given your predefined function:You can implement it in your class like this:
Note the
pre=True
argument passed to the validator. It means that it will be run before the default validator that checks ifsize
is a tuple.Now:
Note that after that, you won't be able to instantiate your
Window
with a tuple for size.In order to overcome that, you could simply bypass the function if a tuple is passed by altering slightly your code:
Pydantic 2.x
Pydantic 1.x
Which should give:
如果您想将转换/验证逻辑保持更模块化或与类本身分离,还有另一个选择。
There is another option if you would like to keep the transform/validation logic more modular or separated from the class itself.