Package: type-serialize
type-serializeSerialize with type annotationsFeaturesSupported in Python 3.8 and later.Serialize classes without additional code.Custom classes@dataclasNamedTupleEnum(Experimental)numpy.ndarrayDeserialization using type annotations.Compress serialization results: bz2, gzip, lzma, zlibNo dependenciesOverviewTo pass a custom object to thejson.dumpsandjson.loadsfunctions,
there is the following method.Expandjson.JSONEncoderandjson.JSONDecoder.Convert to built-in Python object supported byjson.JSONEncoderandjson.JSONDecoder.Both methods require additional code and have some problems.Problem of not checking symbols when manipulating strings.When adding/deleting/editing a property, all related codes must be changed together.Painful typecasting (as the biggest problem).As a way to hide these problems with a library and use serialization and deserialization,
I chosetype annotations.
(Although the library is complicated; haha...) There are some additional advantages to using this.Static type checking usingmypy.Autocomplete in IDE like PyCharm.Things to knowAll public fields are serialized.Methods are not serialized.Private fields that start with an underscore (_) are not serialized.Members specified with the@propertydecorator are not serialized.When deserializing, all fields must be type-annotated.A value ofNoneis ignored by the serialization target.When deserializing, the__init__function must haveNOrequired arguments.Implement__serialize__to override the serialization method.Implement__deserialize__to override the deserialization method.Installationpipinstalltype-serializeIf you want to addnumpy,orjson,msgpack,pyyamlsupport:pipinstalltype-serialize[full]UsageSerializable python objectfromdataclassesimportdataclassfromtype_serializeimportdeserialize,serialize@dataclassclassSample:field1:strfield2:intdata=Sample(field1="a",field2=100)obj=serialize(data)assertisinstance(obj,dict)assertobj["field1"]=="a"assertobj["field2"]==100print(obj)result=deserialize(obj,Sample)assertisinstance(result,Sample)assertdata==resultprint(result)Override serialize and deserializefromdataclassesimportdataclassfromtype_serializeimportdeserialize,serialize@dataclassclassSample:value:intdef__serialize__(self):return{"a":self.value}def__deserialize__(self,data)->None:self.value=data["a"]def__init__(self,value=100):self.value=valuetest=Sample(value=200)obj=serialize(test)assertisinstance(obj,dict)assertobj["a"]==200print(obj)result=deserialize(obj,Sample)assertisinstance(result,Sample)asserttest==resultprint(result)JSON dumps/loadsfromdataclassesimportdataclassfromtype_serialize.jsonimportdumps,loads@dataclassclassSample:field1:strfield2:intdata=Sample(field1="a",field2=100)json_data=dumps(data)print(json_data)result=loads(json_data,Sample)print(result)MsgPack dumps/loadsfromdataclassesimportdataclassfromtype_serialize.msgpackimportdumps,loads@dataclassclassSample:field1:strfield2:intdata=Sample(field1="a",field2=100)json_data=dumps(data)print(json_data)result=loads(json_data,Sample)print(result)Binary encode/decodefromdataclassesimportdataclassfromdatetimeimportdatetimefromtypingimportAny,List,Optionalfromtype_serializeimportdecode,encode@dataclassclassSample:field1:strfield2:Optional[str]=Nonefield3:Optional[List[int]]=Nonefield4:Optional[Any]=Nonefield5:Optional[datetime]=Nonedata=Sample(field1="a",field3=[0,1,2],field4={"k":100},field5=datetime.now(),)raw=encode(data)assertisinstance(raw,bytes)assertlen(raw)>0print(raw)result=decode(raw,Sample)assertisinstance(result,Sample)assertdata==resultprint(result)The encoding format can be adjusted with thecodingargument.fromtype_serializeimportByteCoding,decode,encodedata=...print(encode(data,coding=ByteCoding.MsgpackGzip))encoded_data=...print(decode(encoded_data,coding=ByteCoding.OrjsonZlib))orjson supportIforjsonis installed, it is automatically detected and used.To turn off this option, set theTYPE_SERIALIZE_DISABLE_ORJSON_INSTALLenvironment variable to1.LicenseSee theLICENSEfile for details. In summary,type-serializeis licensed under theMIT license.