Serialize/deserialize Python dataclasses to various other data formats
Project description
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 import dataclass, asdict
from dataclasses_serialization.serializer_base import Serializer, noop_serialization, noop_deserialization, dict_to_dataclass
from toolz import valmap
JSONSerializer = Serializer(
serialization_functions={
dataclass: lambda datacls: JSONSerializer.serialize(asdict(datacls)),
dict: lambda dct: valmap(JSONSerializer.serialize, dct),
list: lambda lst: list(map(JSONSerializer.serialize, lst)),
(str, int, float, bool, type(None)): noop_serialization
},
deserialization_functions={
dataclass: lambda cls, serialized_obj: dict_to_dataclass(cls, serialized_obj, JSONSerializer.deserialize),
(dict, list, str, int, float, bool, type(None)): noop_deserialization
}
)
Reference
dataclasses_serialization.serializer_base
A collection of utilities to make it easier to create serializers.
-
isinstance(o, t)
,issubclass(cls, clsinfo)
Extended versions of the builtin
isinstance
andissubclass
, to treatdataclass
as a metaclass for dataclasses, and to be usable with supportedtyping
types. -
noop_serialization(obj)
,noop_deserialization(cls, obj)
The trivial serialization/deserialization functions, which serialize by doing nothing.
-
dict_to_dataclass(cls, dct, deserialization_func=noop_deserialization)
The inverse of
dataclasses.asdict
, which deserializes a dictionarydct
to a dataclasscls
, usingdeserialization_func
to deserialize the fields ofcls
. -
union_deserialization(type_, obj, deserialization_func=noop_deserialization)
Deserialize a
Union
type_
, by trying each type in turn, and returning the first that does not raise aDeserializationError
.As
Optional
s are implemented asUnion
s, this function also works for them. -
Serializer(serialization_functions, deserialization_functions)
The general serialization class.
Takes two dictionaries of serialization and deserialization functions, and defers to them appropriately when serializing/deserializing and object by the
serialize
anddeserialize
methods. Serializer functions take a single parameter, the object to be serialized, and returns a serialized version of it. Deserializer functions take two parameters, the desired type of the deserialized object, and the object to be deserialized.By default,
Union
s are deserialized usingunion_deserialization
.Serialize a Python object with
serializer.serialize(obj)
, and deserialize withserializer.deserialize(cls, serialized_obj)
. -
SerializationError
,DeserializationError
Errors to be raised when serialization/deserialization fails, respectively.
dataclasses_serialization.json
-
JSONSerializer
Serializer/deserializer between Python dataclasses and JSON objects.
>>> 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)
-
JSONSerializerMixin
Adds
as_json
andfrom_json
methods to dataclasses when used as a mixin.@dataclass class InventoryItem(JSONSerializerMixin): ...
>>> InventoryItem("Apple", 0.2, 20).as_json() {'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20} >>> InventoryItem.from_json({'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20}) InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)
-
JSONStrSerializer
Serializer/deserializer between Python dataclasses and JSON strings.
>>> JSONStrSerializer.serialize(InventoryItem("Apple", 0.2, 20)) '{"name": "Apple", "unit_price": 0.2, "quantity_on_hand": 20}' >>> JSONStrSerializer.deserialize(InventoryItem, '{"name": "Apple", "unit_price": 0.2, "quantity_on_hand": 20}') InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)
-
JSONStrSerializerMixin
Adds
as_json_str
andfrom_json_str
methods to dataclasses when used as a mixin.@dataclass class InventoryItem(JSONStrSerializerMixin): ...
>>> InventoryItem("Apple", 0.2, 20).as_json_str() '{"name": "Apple", "unit_price": 0.2, "quantity_on_hand": 20}' >>> InventoryItem.from_json_str('{"name": "Apple", "unit_price": 0.2, "quantity_on_hand": 20}') InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)
dataclasses_serialization.bson
-
BSONSerializer
Serializer/deserializer between Python dataclasses and BSON objects.
>>> BSONSerializer.serialize(InventoryItem("Apple", 0.2, 20)) {'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20} >>> BSONSerializer.deserialize(InventoryItem, {'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20}) InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)
-
BSONSerializerMixin
Adds
as_bson
andfrom_bson
methods to dataclasses when used as a mixin.@dataclass class InventoryItem(BSONSerializerMixin): ...
>>> InventoryItem("Apple", 0.2, 20).as_bson() {'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20} >>> InventoryItem.from_bson({'name': 'Apple', 'unit_price': 0.2, 'quantity_on_hand': 20}) InventoryItem(name='Apple', unit_price=0.2, quantity_on_hand=20)
-
BSONStrSerializer
Serializer/deserializer between Python dataclasses and binary BSON strings.
-
BSONStrSerializerMixin
Adds
as_bson_str
andfrom_bson_str
methods to dataclasses when used as a mixin.@dataclass class InventoryItem(BSONStrSerializerMixin): ...
Installation
Install and update using the standard Python package manager pip:
pip install dataclasses_serialization
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for dataclasses_serialization-1.0.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 67125564ee93fd6185723753ba58c62bd7e9e944af66f1c937704f96457f9b94 |
|
MD5 | b49f8a6cafa35f999e0eef5d044b6421 |
|
BLAKE2b-256 | a30b06ad61ca921e823ddedca14ac5cbd43eac91edc3a59aa27dd4e204bfe710 |
Hashes for dataclasses_serialization-1.0.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5bac3a78510bda02d6cde6df3fc5af2ae8a034909e16523d3adc3933093f4a04 |
|
MD5 | d1c3c709dab981b0d7e1737500833c64 |
|
BLAKE2b-256 | cc2da271ba193878832001d62dd0f310ba04f405bd5e13c63dcc22791c4c9ea3 |