Skip to main content

Marshmallow-Polyfield

Build Status Coverage Status

This branch supports Marshmallow 3.0 and above. For 2.0 support see The 2.0 branch

An unofficial extension to Marshmallow to allow for polymorphic fields.

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

This project adds a custom field designed for polymorphic types. This allows you to define a schema that says “This field accepts anything of type X”

The secret to this field is that you need to define two functions. One to be used when serializing, and another for deserializing. These functions take in the raw value and return the schema to use.

This field should support the same properties as other Marshmallow fields. I have worked with required allow_none and many.

Last version support v2 is tagged FINAL_V2_VERSION

Installing

$ pip install marshmallow-polyfield

Importing

Here is how to import the necessary field class

from marshmallow_polyfield import PolyField

Example

The code below demonstrates how to setup a schema with a PolyField. 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.

def shape_schema_serialization_disambiguation(base_object, parent_obj):
    class_to_schema = {
        Rectangle.__name__: RectangleSchema,
        Triangle.__name__: TriangleSchema
    }
    try:
        return class_to_schema[base_object.__class__.__name__]()
    except KeyError:
        pass

    raise TypeError("Could not detect type. "
                    "Did not have a base or a length. "
                    "Are you sure this is a shape?")


def shape_schema_deserialization_disambiguation(object_dict, parent_object_dict):
    if object_dict.get("base"):
        return TriangleSchema()
    elif object_dict.get("length"):
        return RectangleSchema()

    raise TypeError("Could not detect type. "
                    "Did not have a base or a length. "
                    "Are you sure this is a shape?")


class ContrivedShapeClass(object):
    def __init__(self, main, others):
        self.main = main
        self.others = others

    def __eq__(self, other):
        return self.__dict__ == other.__dict__


class ContrivedShapeClassSchema(Schema):
    main = PolyField(
        serialization_schema_selector=shape_schema_serialization_disambiguation,
        deserialization_schema_selector=shape_schema_deserialization_disambiguation,
        required=True
    )
    others = PolyField(
        serialization_schema_selector=shape_schema_serialization_disambiguation,
        deserialization_schema_selector=shape_schema_deserialization_disambiguation,
        allow_none=True,
        many=True
    )

    @post_load
    def make_object(self, data):
        return TestPolyField.ContrivedShapeClass(
            data.get('main'),
            data.get('others')
        )

Metadata

Release files for marshmallow-polyfield 5.11

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for marshmallow-polyfield 5.11
File Size Uploaded
marshmallow-polyfield-5.11.tar.gz 8.6 kB Details

Release files / marshmallow-polyfield-5.11.tar.gz

Download URL marshmallow-polyfield-5.11.tar.gz
Size 8.6 kB
Tags Source
SHA-256 checksum
How to use checksums
8075a9cc490da4af58b902b4a40a99882dd031adb7aaa96abd147a4fcd53415f
BLAKE2b-256 checksum
How to use checksums
0e55b752d034a09afe34d680c65cf8634c0c55f9b57e7a673774bc13ca44b53e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.6

Release history Release notifications | RSS feed

This release

5.11 This release

1 release file

5.10

2 release files

5.9

1 release file

5.8

2 release files

5.7

1 release file

5.6

1 release file

5.5

1 release file

5.4

1 release file

5.3

1 release file

5.2

1 release file

5.1

1 release file

5.0

1 release file

4.2

1 release file

3.2

3 release files

3.1

1 release file

3.0

1 release file

2.7

1 release file

2.6

1 release file

2.5

1 release file

2.4

1 release file

2.3

1 release file

2.2

1 release file

2.1

1 release file

2.0

1 release file

1.0

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page