Search code examples
pythonserializationpolymorphismmarshmallow

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()]  # <- !

Solution

  • 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.