Skip to main content

marshmallow multiplexing schema

Project description

Build Status marshmallow 3 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-2.0.1.tar.gz (5.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

marshmallow_oneofschema-2.0.1-py2.py3-none-any.whl (5.7 kB view details)

Uploaded Python 2Python 3

File details

Details for the file marshmallow-oneofschema-2.0.1.tar.gz.

File metadata

  • Download URL: marshmallow-oneofschema-2.0.1.tar.gz
  • Upload date:
  • Size: 5.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.2

File hashes

Hashes for marshmallow-oneofschema-2.0.1.tar.gz
Algorithm Hash digest
SHA256 b88daa4f2de249e0a51a617aa09490f896acaddef6f6cf97dda78218c5abb86f
MD5 17bcbffa460a168471d1e0c85d0cb7db
BLAKE2b-256 a76f709688e46ae54eb87e618c5a3a56aae125da0eafdaa3adc661c8bf91ddc8

See more details on using hashes here.

File details

Details for the file marshmallow_oneofschema-2.0.1-py2.py3-none-any.whl.

File metadata

  • Download URL: marshmallow_oneofschema-2.0.1-py2.py3-none-any.whl
  • Upload date:
  • Size: 5.7 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.2 CPython/3.7.2

File hashes

Hashes for marshmallow_oneofschema-2.0.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 29673bcc415f4a2098e273bf3c8229bc1a33e91378885eac90b06943bd626110
MD5 a72c6271fd2a1bb5115206e9a27df0de
BLAKE2b-256 7af3da71ec4c539b6b5e16f1988fc46d8ea3374e258ef79fb5a7d88478fb922f

See more details on using hashes here.

Supported by

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