与Pydantic验证递归结合
考虑以下列表:
from pydantic.dataclasses import dataclass
from typing import Tuple, Union
@dataclass
class A:
name: str
collection: Tuple[Union["A", int], ...]
A.__pydantic_model__.update_forward_refs()
# Does not work:
c = A("name", (A("a", tuple()), 42,))
创建a
的实例时,验证失败了:
pydantic.error_wrappers.ValidationError: 2 validation errors for A
collection -> 0
value is not a valid dict (type=type_error.dict)
collection -> 0
value is not a valid integer (type=type_error.integer)
此处的问题是pydantic
不考虑a
是验证a
的实例时,有效的项目。例如,如果我删除a
项目,则验证可以通过:
# Works fine:
c = A("name", (42,))
这是一个错误吗?如何使用pydantic
验证递归工会?
Consider the following listing:
from pydantic.dataclasses import dataclass
from typing import Tuple, Union
@dataclass
class A:
name: str
collection: Tuple[Union["A", int], ...]
A.__pydantic_model__.update_forward_refs()
# Does not work:
c = A("name", (A("a", tuple()), 42,))
When an instance of A
is created, validation fails with:
pydantic.error_wrappers.ValidationError: 2 validation errors for A
collection -> 0
value is not a valid dict (type=type_error.dict)
collection -> 0
value is not a valid integer (type=type_error.integer)
The issue here is that pydantic
does not consider A
to be a valid item when validating an instance of A
. For instance, if I remove the A
item, validation passes just fine:
# Works fine:
c = A("name", (42,))
Is this a bug? How do I validate recursive unions with pydantic
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论