Skip to main content

marshmallow multiplexing schema

Project description

PyPI package Build status marshmallow 3|4 compatible

An extension to marshmallow to support schema (de)multiplexing.

marshmallow is a fantastic library for serialization and deserialization of data. For more on that project see its GitHub page or its Documentation.

This library adds a special kind of schema that actually multiplexes other schemas based on object type. When serializing values, it uses get_obj_type() method to get object type name. Then it uses type_schemas name-to-Schema mapping to get schema for that particular object type, serializes object using that schema and adds an extra field with name of object type. Deserialization is reverse.

Installing

$ pip install marshmallow-oneofschema

Example

The code below demonstrates how to set up a polymorphic schema. For the full context check out the tests. Once setup the schema should act like any other schema. If it does not then please file an Issue.

import marshmallow
import marshmallow.fields
from marshmallow_oneofschema import OneOfSchema


class Foo:
    def __init__(self, foo):
        self.foo = foo


class Bar:
    def __init__(self, bar):
        self.bar = bar


class FooSchema(marshmallow.Schema):
    foo = marshmallow.fields.String(required=True)

    @marshmallow.post_load
    def make_foo(self, data, **kwargs):
        return Foo(**data)


class BarSchema(marshmallow.Schema):
    bar = marshmallow.fields.Integer(required=True)

    @marshmallow.post_load
    def make_bar(self, data, **kwargs):
        return Bar(**data)


class MyUberSchema(OneOfSchema):
    type_schemas = {"foo": FooSchema, "bar": BarSchema}

    def get_obj_type(self, obj):
        if isinstance(obj, Foo):
            return "foo"
        elif isinstance(obj, Bar):
            return "bar"
        else:
            raise Exception("Unknown object type: {}".format(obj.__class__.__name__))


MyUberSchema().dump([Foo(foo="hello"), Bar(bar=123)], many=True)
# => [{'type': 'foo', 'foo': 'hello'}, {'type': 'bar', 'bar': 123}]

MyUberSchema().load(
    [{"type": "foo", "foo": "hello"}, {"type": "bar", "bar": 123}], many=True
)
# => [Foo('hello'), Bar(123)]

By default get_obj_type() returns obj.__class__.__name__, so you can just reuse that to save some typing:

class MyUberSchema(OneOfSchema):
    type_schemas = {"Foo": FooSchema, "Bar": BarSchema}

You can customize type field with type_field class property:

class MyUberSchema(OneOfSchema):
    type_field = "object_type"
    type_schemas = {"Foo": FooSchema, "Bar": BarSchema}


MyUberSchema().dump([Foo(foo="hello"), Bar(bar=123)], many=True)
# => [{'object_type': 'Foo', 'foo': 'hello'}, {'object_type': 'Bar', 'bar': 123}]

You can use resulting schema everywhere marshmallow.Schema can be used, e.g.

import marshmallow as m
import marshmallow.fields as f


class MyOtherSchema(m.Schema):
    items = f.List(f.Nested(MyUberSchema))

License

MIT licensed. See the bundled LICENSE file for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

marshmallow_oneofschema-3.2.0.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

marshmallow_oneofschema-3.2.0-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file marshmallow_oneofschema-3.2.0.tar.gz.

File metadata

File hashes

Hashes for marshmallow_oneofschema-3.2.0.tar.gz
Algorithm Hash digest
SHA256 c06c8d9f14d51ffff152d66d85bd5f27d55cff10752a3b1f8c1f948bf5f597a0
MD5 c2138f06bef96e2aafdd648ac3219636
BLAKE2b-256 bb42a0e00dea6a831acfe9d3fe664d695b7cefc02c27dd69d9ccb4bdc3c3d1a7

See more details on using hashes here.

Provenance

The following attestation bundles were made for marshmallow_oneofschema-3.2.0.tar.gz:

Publisher: build-release.yml on marshmallow-code/marshmallow-oneofschema

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file marshmallow_oneofschema-3.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for marshmallow_oneofschema-3.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 19c87e6124ef05e2831e5c631168c909a50a8fe399921b9841b75fef3785be8c
MD5 d6ebbaa6a4d3c4337fb0ad32e8bb4cab
BLAKE2b-256 711552d6ac14dcfe381e4f1c204c9c287623b8b462bc27c6cc468dba0560ed4c

See more details on using hashes here.

Provenance

The following attestation bundles were made for marshmallow_oneofschema-3.2.0-py3-none-any.whl:

Publisher: build-release.yml on marshmallow-code/marshmallow-oneofschema

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page