Marshmallow OneOfSchema

3.2.0 · active · verified Thu Apr 09

marshmallow-oneofschema provides polymorphic schema capabilities for Marshmallow, allowing a single schema to serialize and deserialize objects of different types based on a discriminator field. The current version is 3.2.0, and it follows the release cadence of the core Marshmallow library, with stable and well-tested releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a `OneOfSchema` to handle different types of pet objects (Cat and Dog). It shows how to map type identifiers to specific Marshmallow schemas using `type_schemas` and how to specify the discriminator field using `type_field`. It also includes examples of both serialization (`dump`) and deserialization (`load`), and demonstrates handling an unknown type during deserialization.

from marshmallow import Schema, fields
from marshmallow_oneofschema import OneOfSchema

class CatSchema(Schema):
    name = fields.String(required=True)
    lives = fields.Integer(load_default=9)

class DogSchema(Schema):
    name = fields.String(required=True)
    breed = fields.String()

class PetSchema(OneOfSchema):
    type_schemas = {
        "cat": CatSchema,
        "dog": DogSchema,
    }
    type_field = "pet_type" # Discriminator field in input data

# Example data
cat_data = {"pet_type": "cat", "name": "Whiskers", "lives": 7}
dog_data = {"pet_type": "dog", "name": "Buddy", "breed": "Golden Retriever"}
unknown_pet_data = {"pet_type": "fish", "name": "Nemo"}

# Instantiate the polymorphic schema
pet_schema = PetSchema()

# Serialization (dump)
serialized_cat = pet_schema.dump(cat_data)
print(f"Serialized Cat: {serialized_cat}")

serialized_dog = pet_schema.dump(dog_data)
print(f"Serialized Dog: {serialized_dog}")

# Deserialization (load)
loaded_cat = pet_schema.load(serialized_cat)
print(f"Loaded Cat: {loaded_cat}")

loaded_dog = pet_schema.load(serialized_dog)
print(f"Loaded Dog: {loaded_dog}")

try:
    # This will raise a ValidationError because 'fish' is not in type_schemas
    pet_schema.load(unknown_pet_data)
except Exception as e:
    print(f"Error loading unknown type: {e}")

view raw JSON →