如何在Python中创建一个键入列表
我正在尝试使用Pydantic在Python中创建一个键入列表。我的第一个想法是做这样的事情:
class TypedObject(pydantic.BaseModel):
# some attributes and methods here
pass
class TypedList(pydantic.BaseModel):
items: List[TypedObject]
# some other methods here
但是,typedlist
不是真正的列表,而是一个围绕一个列表。我实际上想要的是typedlist
从list [typedObject]
之类的东西继承,以便我获得实际列表,但请保留其元素的pydantic验证。
这是可能的(不必从裸露的列表中继承并覆盖Dunder方法以解析对象吗?)
谢谢您!
I am trying to create a typed list in Python using pydantic. My first idea was to do something like this:
class TypedObject(pydantic.BaseModel):
# some attributes and methods here
pass
class TypedList(pydantic.BaseModel):
items: List[TypedObject]
# some other methods here
However, TypedList
is not really a list but a wrapper around one. What I would actually like is TypedList
to inherit from something like List[TypedObject]
, so that I get an actual list but keep the pydantic validation for its elements.
Is this possible (without having to inherit from a naked list and overriding the dunder methods to parse the objects?)
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可能正在寻找“ nofollow noreferrer”>“自定义根类型” ,尽管这只会让您纳入其中。
如果我们定义了这样的模型:
然后,当我们初始化
widgetList
这样的时:这样序列化:
我们可以使用
parse_obj
方法来创建widgetList
来自a列表:
不幸的是,我们不能将其视为列表;我们需要
显式参考
__ root __
创建它(如上图)或尝试访问列表成员时:
I think you may be looking for "Custom root types", although that only gets you part way there.
If we define a model like this:
Then when we initialize an
WidgetList
like this:It serializes like this:
We we can use the
parse_obj
method to create aWidgetList
from alist:
Unfortunately, we can't otherwise treat it as a list; we need to
explicitly reference
__root__
when creating it (as seen above) orwhen attempting to access list members: