Registry / serialization / marshmallow-oneofschema

marshmallow-oneofschema

JSON →
library3.2.0pypypi✓ verified 25d ago

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-oneofschema
INSTALL
IMPORT
SIG · MARSHMALLOW-ONEOFS
M
marshmallow-oneofschema
serializationpythonv3.2.0
Install
1.8s avg
Import
570ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.2.0 · 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.95 runs
installs and imports cleanly · install 0.0s · import 0.572s · 18.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.568s · 19MB
16MB installed
● package 16MB
Code
Verified usage

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

OneOfSchema
from marshmallow_oneofschema import OneOfSchema

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}")
Debug
Known issues
breakingmarshmallow-oneofschema v2.0.0 and later require Marshmallow v3.x. Attempting to use it with Marshmallow v2.x will result in `ImportError` or other runtime errors due to API changes in Marshmallow.
fix
Ensure your project's Marshmallow dependency is `marshmallow>=3.0.0`. Upgrade Marshmallow if necessary (e.g., `pip install 'marshmallow>=3.0.0'`).
affects: >=2.0.0
breakingThe API for defining polymorphic schemas changed significantly in v2.0.0. The `type_map` attribute was removed and replaced by `type_schemas` and `type_field` for clearer definition of type mappings and the discriminator field.
fix
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'`.
affects: >=2.0.0
gotchaIncorrectly specifying or omitting the `type_field` attribute or providing data without this field will lead to deserialization failures (`ValidationError`), as `OneOfSchema` won't know which sub-schema to use.
fix
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`.
affects: all
gotchaAttempting to serialize or deserialize an object whose type (as indicated by `type_field`) is not present as a key in the `type_schemas` dictionary will result in an error (`ValueError` for dump, `ValidationError` for load).
fix
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.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'marshmallow_oneofschema'
The `marshmallow-oneofschema` library has not been installed in your Python environment.
fix
Install the library using pip: `pip install marshmallow-oneofschema`
ImportError: cannot import name 'MarshalResult' from 'marshmallow'
This error typically occurs when using an older version of `marshmallow-oneofschema` (e.g., pre-3.0.0) with Marshmallow 3.x or newer. `MarshalResult` and `UnmarshalResult` were removed from the top-level `marshmallow` import in Marshmallow 3.
fix
Upgrade `marshmallow-oneofschema` to version 3.0.0 or higher to ensure compatibility with Marshmallow 3+: `pip install --upgrade marshmallow-oneofschema`
ValidationError: {'<discriminator_field>': ['<discriminator_field> has unknown type <value>']}
This validation error occurs during deserialization when the value provided for the discriminator field (e.g., 'type') does not match any of the keys defined in the `type_schemas` mapping of your `OneOfSchema`.
fix
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.
Upgrade
Version history
3.2.0latest on PyPI · released May 8, 2025
Audit
Dependencies
marshmallowrequiredCore dependency for schema definition and processing.
Agent activity
8 hits · last 30 days
node
6
Resources
marshmallow-oneofschema — pip install marshmallow-oneofschema · libregistry