Mr. B.
Mr. B.

Reputation: 8717

Python marshmallow: how to allow multiple Schemas to a Schema's field?

I'd like to declare a schema field to accept different schema types, but not any.

Is something like the following possible with Marshmallow?

class SchemaA(Schema):
    name = String()

class SchemaB(Schema):
    name = String()
    age = Integer()

class SchemaC(Schema)
    one_of_many_but_not_any = [SchemaA(), SchemaB(), String()]  # <- !

Upvotes: 5

Views: 5810

Answers (1)

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 14714

What you want to achieve is referred to as polymorphism.

This is not supported by marshmallow yet but it is a recurrent question and I've been tagging all related issues in the bugtracker with the polymorphism tag.

See for instance https://github.com/marshmallow-code/marshmallow/issues/1255.

There are currently two libs adding this support:

They both have their pros/cons.

Upvotes: 4

Related Questions