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-unionVerified import paths — ran on the pinned version, not inferred.
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.
Order your fields carefully, placing more specific or strict types before more general ones. Alternatively, use `marshmallow-polyfield` for explicit type-based dispatch.
Ensure that your data conforms to at least one of the union's candidate fields during serialization, or implement error handling for `ExceptionGroup`.
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`.
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.
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.
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.
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.