Marshmallow Union

0.1.15.post1 · maintenance · verified Mon Apr 13

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.

Warnings

Install

Imports

Quickstart

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

view raw JSON →