Pydantic: Proper way to serialize list object

Created on 13 Feb 2020  路  6Comments  路  Source: samuelcolvin/pydantic

Question

In marshamllow or drf serializer has many=True options for list object.

But pydantic seems does not have this option.

So after searched about it, I found ways through __root__

class UserList(BaseModel):
    __root__: List[User]

UserList.parse_obj([
    {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']},
    {'id': '456', 'signup_ts': '2017-06-02 12:22', 'friends': ['you']},
])

I wonder that, is it a official way to serialize list object?

feature request help wanted question

All 6 comments

Yes, that's correct, you could also use parse_as_obj.

I guess we could add a many argument to parse_obj?

@samuelcolvin Any plans to add that options soon?

shouldn't be too hard, PR welcome to add it.

If you agree with the many kwarg to parse_* functions, this should stay open until it's implemented.

Humm, sorry to change my mind, but I'm now not at all sure the many argument is really a good idea.

Reasons:

  • it will mean a variable return type (we can fix that with @override, but still)
  • it makes the model interface even more complicated
    We have parse_obj_as for purposes like this
  • I want to significantly simplify/clean the parse_* methods in v2 which could conflict with this

@tiangolo @dmontagu I'd appreciate your thoughts?

I agree with you @samuelcolvin , I'm actually not a fan of the many, as it doesn't play well with types.

It would probably also conflict (at least mentally) with List[Model], in model fields or the new (awesome) function decorator you've been working on; and the __root__ option.

So, yeah, my vote would actually be against adding a many option. :grimacing:

On the other side, for users that need something like that, with the new function decorator I'm pretty sure you will be able to:

@validate_arguments
def my_func(my_objs: List[MyModel]):
    for obj in my_objs:
        print(obj)  # or do whatever you need

Also, if you are using FastAPI, it already works like that, as it can use Pydantic's internals.


As a side note, taking aside that I was a big fan of Marshmallow (as it inspired a lot of FastAPI, etc), I actually liked that Pydantic didn't have a many option.

Once you start using many in some places and not in others it can get confusing as some things end up as sequences while others are scalars, and it's not that obvious from the code, and more importantly, it doesn't play well with type annotations.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gangefors picture gangefors  路  3Comments

cdeil picture cdeil  路  3Comments

nav picture nav  路  3Comments

samuelcolvin picture samuelcolvin  路  3Comments

timonbimon picture timonbimon  路  3Comments