marshmallow-polyfield is an unofficial extension to Marshmallow (version 3+) that enables defining polymorphic fields within your schemas. It allows for serialization and deserialization of objects that can have different underlying types, mapping them to appropriate Marshmallow schemas based on a discriminator field. The current version is 5.11, and it maintains an active release cadence to ensure compatibility with recent Marshmallow versions.
pip install marshmallow-polyfieldVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `PolyField` to handle polymorphic objects. It defines `Dog` and `Cat` classes with corresponding `DogSchema` and `CatSchema`. The `AnimalSchema` then uses `PolyField` with `deserialization_schema_map`, `serialization_schema_map`, and a `lookup_field` to correctly map between object types and schemas during both serialization and deserialization. The `lookup_field` ('animal_type' in this case) is crucial for `marshmallow-polyfield` to determine which concrete schema to use.
Ensure your project explicitly installs `marshmallow>=3.0.0`. If migrating an existing Marshmallow 2.x project, consult Marshmallow's official migration guide first.
Double-check that the string value returned by `lookup_field` (or present in your input data) precisely matches one of the keys in `deserialization_schema_map` and `serialization_schema_map`.
Always provide both `deserialization_schema_map` and `serialization_schema_map` to `PolyField` for complete functionality. Ensure the keys and values align with your expected object types and schemas.
Upgrade your `marshmallow` dependency to version 3.x or higher: `pip install --upgrade marshmallow`
Verify that the `lookup_field` name in your `PolyField` definition matches the key in your input data, and that its value corresponds to a key in `deserialization_schema_map`.
Add the `lookup_field` argument to your `PolyField` instantiation, specifying the name of the field that determines the object's type (e.g., `lookup_field='object_type'`).