Registry / serialization / marshmallow-union

marshmallow-union

JSON →
library0.1.15.post1pypypi✓ verified 22d ago

marshmallow-union provides a `Union` field for Marshmallow schemas, allowing a single field to accept and serialize/deserialize values that conform to one of several specified field types. The library works by trying a list of fields one by one until one succeeds. The current version is 0.1.15.post1, released in June 2020, indicating a maintenance or inactive release cadence.

pip install marshmallow-union
INSTALL
IMPORT
SIG · MARSHMALLOW-UNION
M
marshmallow-union
serializationpythonv0.1.15.post1
Install
1.7s avg
Import
545ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.1.15.post1 · 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.548s · 18.7MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.7s · import 0.542s · 19MB
16MB installed
● package 16MB
Code
Verified usage

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

Union
from marshmallow_union import Union

This quickstart demonstrates how to define a `Union` field in a Marshmallow schema and perform both deserialization (loading) and serialization (dumping) of data containing either an integer or a string. It also shows how validation errors are raised for unsupported types.

import marshmallow from marshmallow import Schema, fields, ValidationError from marshmallow_union import Union class MySchema(Schema): id = fields.Integer(required=True) value = Union(fields=[fields.Integer(), fields.String()], required=True) # Deserialization (loading) data_int = {'id': 1, 'value': 123} data_str = {'id': 2, 'value': 'hello'} data_invalid = {'id': 3, 'value': []} schema = MySchema() # Load an integer value loaded_int = schema.load(data_int) print(f"Loaded Int: {loaded_int}") assert loaded_int == {'id': 1, 'value': 123} # Load a string value loaded_str = schema.load(data_str) print(f"Loaded String: {loaded_str}") assert loaded_str == {'id': 2, 'value': 'hello'} # Attempt to load an invalid value try: schema.load(data_invalid) except ValidationError as e: print(f"Validation Error: {e.messages}") assert 'value' in e.messages # Serialization (dumping) dumped_int = schema.dump(loaded_int) print(f"Dumped Int: {dumped_int}") assert dumped_int == data_int dumped_str = schema.dump(loaded_str) print(f"Dumped String: {dumped_str}") assert dumped_str == data_str
Debug
Known issues
gotchaThe `Union` field deserializes/serializes by trying fields in the order they are provided until one successfully processes the value without raising an error. This can lead to unexpected behavior if an earlier field accepts an unintended type (e.g., `fields.Integer()` might accept a string like '123'). For precise control over type matching, consider using `marshmallow-polyfield` instead.
fix
Order your fields carefully, placing more specific or strict types before more general ones. Alternatively, use `marshmallow-polyfield` for explicit type-based dispatch.
affects: <=0.1.15.post1
breakingStarting from version 0.1.12, if all candidate fields within a `Union` fail during serialization, a `marshmallow_union.ExceptionGroup` is raised. Prior versions might have behaved differently, possibly returning `None` or an empty dictionary.
fix
Ensure that your data conforms to at least one of the union's candidate fields during serialization, or implement error handling for `ExceptionGroup`.
affects: >=0.1.12
gotchaWhen using `Union` with `Nested` schemas, the serialization process still follows the 'first successful match' logic. If the first nested schema in the `Union` successfully processes *some* part of the input (even if not fully matching the intended type), subsequent nested schemas for other types will not be attempted, potentially leading to incomplete or incorrect dumps (e.g., an empty dictionary for the nested field).
fix
For nested schemas, you might need to implement a custom `dump` method or mixin within your nested schemas to ensure they explicitly raise an error if the object type doesn't match, forcing the `Union` to try the next candidate. See GitHub Issue #38 for a suggested `UnionMemberMixin`.
affects: <=0.1.15.post1
gotchaThe library has not been updated since June 2020. This means it may have compatibility issues with newer versions of Marshmallow (e.g., Marshmallow 4.x, released in April 2026), which introduced significant breaking changes in field usage, validation, and serialization behavior.
fix
Pin your `marshmallow` dependency to a compatible version (e.g., `marshmallow<4.0`). Thoroughly test `marshmallow-union` functionality if upgrading `marshmallow` to a major new version.
affects: Marshmallow >3.x
Errors
Common errors & fixes
marshmallow_union.ExceptionGroup: All fields in the union failed to deserialize/serialize.
This error occurs when `marshmallow-union` attempts to deserialize or serialize a value, and none of the fields provided in the `Union` field definition successfully process the value without raising an exception.
fix
Ensure that the input data conforms to at least one of the field types specified in the `Union`. If a specific field should handle the data, verify its validation rules and data format. Consider using `marshmallow-polyfield` for more precise control over type dispatch if implicit type matching is problematic.
TypeError: Field for "my_field" must be declared as a Field instance, not a class. Did you mean "fields.String()"?
This is a common Marshmallow error (not specific to `marshmallow-union`, but often encountered when defining `Union` fields) where a field class (e.g., `marshmallow.fields.String`) is passed to the schema instead of an instantiated field object (e.g., `marshmallow.fields.String()`).
fix
Instantiate each field within the `Union`'s list by adding parentheses to the field class, converting `fields.String` to `fields.String()`, `fields.Integer` to `fields.Integer()`, etc.
marshmallow-union Nested serialization always chooses the first type, resulting in incorrect or empty output like `{'my_union_field': {}}`.
When using `Union` with `Nested` schemas, `marshmallow-union`'s default behavior tries fields in order and stops at the first one that doesn't raise an exception during serialization. If the first `Nested` schema partially matches or processes the input without error, it might be chosen even if the data truly belongs to a later schema in the list, leading to incorrect or empty serialization if the chosen schema doesn't fully match the data.
fix
Implement a custom `dump` method within the nested schemas (e.g., using a mixin) that performs explicit validation and raises a `ValueError` or `ValidationError` if the object is not valid for that specific schema. This forces `Union` to skip to the next candidate field if the current one is not truly appropriate for the data.
Upgrade
Version history
0.1.15.post1latest on PyPI · released Jun 24, 2020
Audit
Dependencies
marshmallowrequiredCore dependency for schema definition and serialization/deserialization.
Agent activity
3 hits · last 30 days
node
2
Resources
marshmallow-union — pip install marshmallow-union · libregistry