Package: dataclasses-serialization
dataclasses_serializationdataclasses_serializationprovides serializers/deserializers for transforming between Python dataclasses, and JSON and BSON objects.Basic UsageSuppose we have the following dataclass:fromdataclassesimportdataclass@dataclassclassInventoryItem:name:strunit_price:floatquantity_on_hand:intThen we may serialize/deserialize it to/from JSON by usingJSONSerializer>>>fromdataclasses_serialization.jsonimportJSONSerializer>>>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)MongoAs Mongo collections store objects as BSON, you can useBSONSerializerto dump dataclasses directly into Mongo.fromdataclasses_serialization.bsonimportBSONSerializercollection.insert_one(BSONSerializer.serialize(item))item=BSONSerializer.deserialize(InventoryItem,collection.find_one())Custom SerializersTo create a custom serializer, create an instance ofdataclasses_serialization.serializer_base.Serializer:fromdataclasses_serialization.serializer_baseimportnoop_serialization,noop_deserialization,dict_serialization,dict_deserialization,list_deserialization,SerializerJSONSerializer=Serializer(serialization_functions={dict:lambdadct:dict_serialization(dct,key_serialization_func=JSONSerializer.serialize,value_serialization_func=JSONSerializer.serialize),list:lambdalst:list(map(JSONSerializer.serialize,lst)),(str,int,float,bool,type(None)):noop_serialization},deserialization_functions={dict:lambdacls,dct:dict_deserialization(cls,dct,key_deserialization_func=JSONSerializer.deserialize,value_deserialization_func=JSONSerializer.deserialize),list:lambdacls,lst:list_deserialization(cls,lst,deserialization_func=JSONSerializer.deserialize),(str,int,float,bool,type(None)):noop_deserialization})Referencedataclasses_serialization.serializer_baseA collection of utilities to make it easier to create serializers.isinstance(o, t),issubclass(cls, clsinfo)Extended versions of the builtinisinstanceandissubclass, to treatdataclassas a superclass for dataclasses, and to be usable with supportedtypingtypes.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 ofdataclasses.asdict, which deserializes a dictionarydctto a dataclasscls, usingdeserialization_functo deserialize the fields ofcls.Fields are deserialized using the type provided by the dataclass.
So bound generic dataclasses may be deserialized, while unbound ones may not.union_deserialization(type_, obj, deserialization_func=noop_deserialization)Deserialize aUniontype_, by trying each type in turn, and returning the first that does not raise aDeserializationError.AsOptionals are implemented asUnions, this function also works for them.dict_serialization(obj, key_serialization_func=noop_serialization, value_serialization_func=noop_serialization),dict_deserialization(type_, obj, key_deserialization_func=noop_deserialization, value_deserialization_func=noop_deserialization)Serialize/deserialize a dictionaryobjby applying the appropriate serialization/deserialization functions to keys and values.list_deserialization(type_, obj, deserialization_func=noop_deserialization)Deserialize a listobjby applying the deserialization function to its values.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 theserializeanddeserializemethods.
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.If an object's type cannot be found directly in the serialization/deserialization functions, theSerializeruses its closest ancestor - raising an error in case of ambiguity.By defaultdataclasses are serialized as though they aredicts.
Similarly,dataclasses are deserialized usingdict_to_dataclass, andUnions usingunion_deserialization, using itself as the nested deserialization function.Serialize a Python object withserializer.serialize(obj), and deserialize withserializer.deserialize(cls, serialized_obj).Register more serialization/deserialization functions withserializer.register_serializer(cls, func),serializer.register_deserializer(cls, func), andserializer.register(cls, serialization_func, deserialization_func).
They can also be used as decorators like so:@serializer.register_serializer(int)defint_serializer(obj):...@serializer.register_deserializer(int)defint_deserializer(cls,obj):...SerializationError,DeserializationErrorErrors to be raised when serialization/deserialization fails, respectively.dataclasses_serialization.jsonJSONSerializerSerializer/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)JSONSerializerMixinAddsas_jsonandfrom_jsonmethods to dataclasses when used as a mixin.@dataclassclassInventoryItem(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)JSONStrSerializerSerializer/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)JSONStrSerializerMixinAddsas_json_strandfrom_json_strmethods to dataclasses when used as a mixin.@dataclassclassInventoryItem(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.bsonBSONSerializerSerializer/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)BSONSerializerMixinAddsas_bsonandfrom_bsonmethods to dataclasses when used as a mixin.@dataclassclassInventoryItem(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)BSONStrSerializerSerializer/deserializer between Python dataclasses and binary BSON strings.BSONStrSerializerMixinAddsas_bson_strandfrom_bson_strmethods to dataclasses when used as a mixin.@dataclassclassInventoryItem(BSONStrSerializerMixin):...InstallationInstall and update using the standard Python package managerpip:pipinstalldataclasses_serialization