Registry / serialization / marshmallow-polyfield

marshmallow-polyfield

JSON →
library5.11pypypi✓ verified 85d ago

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-polyfield
INSTALL
IMPORT
SIG · MARSHMALLOW-POLYFI
M
marshmallow-polyfield
serializationpythonv5.11
Install
2.5s avg
Import
577ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v5.11 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.570s · 20.1MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.5s · import 0.584s · 21MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PolyField
from marshmallow_polyfield import PolyField
PolySchema
from marshmallow_polyfield import PolySchema
Less commonly used for simple polymorphic fields; PolyField is more direct.

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.

from marshmallow import Schema, fields from marshmallow_polyfield import PolyField class Dog: def __init__(self, name, breed): self.name = name self.breed = breed self.animal_type = 'dog' class Cat: def __init__(self, name, color): self.name = name self.color = color self.animal_type = 'cat' class DogSchema(Schema): name = fields.String(required=True) breed = fields.String(required=True) animal_type = fields.Constant('dog') class CatSchema(Schema): name = fields.String(required=True) color = fields.String(required=True) animal_type = fields.Constant('cat') class AnimalSchema(Schema): animal = PolyField( deserialization_schema_map={ 'dog': DogSchema, 'cat': CatSchema }, serialization_schema_map={ 'dog': DogSchema, 'cat': CatSchema }, lookup_field='animal_type' ) # --- Example Usage --- dog_obj = Dog(name='Buddy', breed='Golden Retriever') cat_obj = Cat(name='Whiskers', color='black') # Serialization poly_schema = AnimalSchema() dog_data = poly_schema.dump({'animal': dog_obj}) cat_data = poly_schema.dump({'animal': cat_obj}) print(f"Serialized Dog: {dog_data}") print(f"Serialized Cat: {cat_data}") # Deserialization dog_dict = {'animal_type': 'dog', 'name': 'Rex', 'breed': 'German Shepherd'} cat_dict = {'animal_type': 'cat', 'name': 'Mittens', 'color': 'white'} deserialized_dog = poly_schema.load({'animal': dog_dict}) deserialized_cat = poly_schema.load({'animal': cat_dict}) print(f"Deserialized Dog type: {type(deserialized_dog['animal'])}") print(f"Deserialized Cat type: {type(deserialized_cat['animal'])}")
Debug
Known issues
breakingmarshmallow-polyfield requires Marshmallow 3.x. Using it with Marshmallow 2.x will lead to various AttributeErrors or unexpected behavior due to significant API changes between Marshmallow major versions.
fix
Ensure your project explicitly installs `marshmallow>=3.0.0`. If migrating an existing Marshmallow 2.x project, consult Marshmallow's official migration guide first.
affects: < 5.7
gotchaIncorrectly configured `lookup_field` or `schema_map` can lead to `KeyError` during deserialization or `ValidationError`. The `lookup_field` value in the data must exactly match a key in your `deserialization_schema_map`.
fix
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`.
affects: All versions
gotcha`marshmallow-polyfield` does not automatically infer the type for serialization. Both `deserialization_schema_map` and `serialization_schema_map` must be provided and correctly configured for bidirectional polymorphism.
fix
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.
affects: All versions
Errors
Common errors & fixes
AttributeError: 'Field' object has no attribute '_declared_fields'
This error often indicates that you are running `marshmallow-polyfield` (which targets Marshmallow 3) with an older version of `marshmallow` (e.g., 2.x).
fix
Upgrade your `marshmallow` dependency to version 3.x or higher: `pip install --upgrade marshmallow`
KeyError: 'type_field_value'
This usually occurs during deserialization when the value of the `lookup_field` in the input data does not match any of the keys defined in your `deserialization_schema_map`.
fix
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`.
TypeError: __init__() missing 1 required positional argument: 'lookup_field'
You've attempted to initialize `PolyField` without providing the mandatory `lookup_field` argument, which tells it which field to use for type discrimination.
fix
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'`).
Upgrade
Version history
5.11latest on PyPI · released Oct 26, 2022
Audit
Dependencies
marshmallowrequiredCore dependency; this library extends Marshmallow's functionality.
Agent activity
2 hits · last 30 days
node
2
Resources
marshmallow-polyfield — pip install marshmallow-polyfield · libregistry