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.
pip install marshmallow-oneofschemaVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your project's Marshmallow dependency is `marshmallow>=3.0.0`. Upgrade Marshmallow if necessary (e.g., `pip install 'marshmallow>=3.0.0'`).
If migrating from v1.x, update your schema definition from `type_map = {'type_name': SchemaClass}` to `type_schemas = {'type_name': SchemaClass}` and explicitly set `type_field = 'discriminator_field_name'`.Always define `type_field` in your `OneOfSchema` subclass, ensuring it matches the field name in your input data that determines the object's type. For input data, make sure the `type_field` is present and its value exactly matches a key in `type_schemas`.
Ensure all possible object types that your `OneOfSchema` might encounter are explicitly listed as keys in `type_schemas`, mapped to their respective Marshmallow schema classes. Handle unknown types upstream if they are not expected to be processed by this schema.
Install the library using pip: `pip install marshmallow-oneofschema`
Upgrade `marshmallow-oneofschema` to version 3.0.0 or higher to ensure compatibility with Marshmallow 3+: `pip install --upgrade marshmallow-oneofschema`
Ensure that the input data's discriminator field value (e.g., `{'type': 'UnknownType'}`) exactly matches a key in your `OneOfSchema`'s `type_schemas` dictionary. Also, verify the discriminator field name (`type_field`) matches the field in your input data.