如何在Python中创建一个键入列表

发布于 2025-02-06 13:00:03 字数 480 浏览 2 评论 0原文

我正在尝试使用Pydantic在Python中创建一个键入列表。我的第一个想法是做这样的事情:

class TypedObject(pydantic.BaseModel):
   # some attributes and methods here
   pass 

class TypedList(pydantic.BaseModel):
    items: List[TypedObject]
    
    # some other methods here

但是,typedlist不是真正的列表,而是一个围绕一个列表。我实际上想要的是typedlistlist [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 技术交流群。

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

发布评论

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

评论(1

清风夜微凉 2025-02-13 13:00:03

我认为您可能正在寻找“ nofollow noreferrer”>“自定义根类型” ,尽管这只会让您纳入其中。

如果我们定义了这样的模型:

import pydantic


class Widget(pydantic.BaseModel):
    name: str


class WidgetList(pydantic.BaseModel):
    __root__: list[Widget]

然后,当我们初始化widgetList这样的时:

>>> w = WidgetList(__root__=[Widget(name='foo'), Widget(name='bar')])

这样序列化:

>>> w.json()
'[{"name": "foo"}, {"name": "bar"}]'

我们可以使用parse_obj方法来创建widgetList来自a
列表:

>>> WidgetList.parse_obj([{"name": "foo"}, {"name": "bar"}])
WidgetList(__root__=[Widget(name='foo'), Widget(name='bar')])

不幸的是,我们不能将其视为列表;我们需要
显式参考__ root __创建它(如上图)或
尝试访问列表成员时:

>>> w.__root__[0]
Widget(name='foo')

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:

import pydantic


class Widget(pydantic.BaseModel):
    name: str


class WidgetList(pydantic.BaseModel):
    __root__: list[Widget]

Then when we initialize an WidgetList like this:

>>> w = WidgetList(__root__=[Widget(name='foo'), Widget(name='bar')])

It serializes like this:

>>> w.json()
'[{"name": "foo"}, {"name": "bar"}]'

We we can use the parse_obj method to create a WidgetList from a
list:

>>> WidgetList.parse_obj([{"name": "foo"}, {"name": "bar"}])
WidgetList(__root__=[Widget(name='foo'), Widget(name='bar')])

Unfortunately, we can't otherwise treat it as a list; we need to
explicitly reference __root__ when creating it (as seen above) or
when attempting to access list members:

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