madman-bob / python-dataclasses-serialization

Serialize/deserialize Python dataclasses to various other data formats
MIT License
25 stars 11 forks source link

dataclasses_serialization

dataclasses_serialization provides serializers/deserializers for transforming between Python dataclasses, and JSON and BSON objects.

Basic Usage

Suppose we have the following dataclass:

from dataclasses import dataclass

@dataclass
class InventoryItem:
    name: str
    unit_price: float
    quantity_on_hand: int

Then we may serialize/deserialize it to/from JSON by using JSONSerializer

>>> from dataclasses_serialization.json import JSONSerializer
>>> JSONSerializer.serialize(InventoryItem("Apple", 0.2, 20))
{'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20}

>>> JSONSerializer.deserialize(InventoryItem, {'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20})
InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)

Mongo

As Mongo collections store objects as BSON, you can use BSONSerializer to dump dataclasses directly into Mongo.

from dataclasses_serialization.bson import BSONSerializer

collection.insert_one(BSONSerializer.serialize(item))

item = BSONSerializer.deserialize(InventoryItem, collection.find_one())

Custom Serializers

To create a custom serializer, create an instance of dataclasses_serialization.serializer_base.Serializer:

from dataclasses_serialization.serializer_base import noop_serialization, noop_deserialization, dict_serialization, dict_deserialization, list_deserialization, Serializer

JSONSerializer = Serializer(
    serialization_functions={
        dict: lambda dct: dict_serialization(dct, key_serialization_func=JSONSerializer.serialize, value_serialization_func=JSONSerializer.serialize),
        list: lambda lst: list(map(JSONSerializer.serialize, lst)),
        (str, int, float, bool, type(None)): noop_serialization
    },
    deserialization_functions={
        dict: lambda cls, dct: dict_deserialization(cls, dct, key_deserialization_func=JSONSerializer.deserialize, value_deserialization_func=JSONSerializer.deserialize),
        list: lambda cls, lst: list_deserialization(cls, lst, deserialization_func=JSONSerializer.deserialize),
        (str, int, float, bool, type(None)): noop_deserialization
    }
)

Reference

dataclasses_serialization.serializer_base

A collection of utilities to make it easier to create serializers.

dataclasses_serialization.json

dataclasses_serialization.bson

Installation

Install and update using the standard Python package manager pip:

pip install dataclasses_serialization