Package: dataclass-codec
dataclass_codecdataclass_codec is a Python library that provides encoding and decoding functions for dictionaries. It allows you to easily convert Python dictionaries to JSON-compatible data structures and vice versa.InstallationYou can install dataclass_codec using pip:pip install dataclass-codecUsagedataclass_codec is designed to work with dictionaries, which are a common way to represent structured data in Python. You can use dataclass_codec to decode dictionaries into Python dataclasses.Here is an example of how to use dataclass_codec with dataclasses:fromdataclassesimportdataclassfromdataclass_codecimportdecode# Define a dataclass@dataclassclassPerson:name:strage:intcity:str# Define a dictionary representing a personperson_dict={"name":"John","age":30,"city":"New York"}# Decode the dictionary into a Person objectperson=decode(person_dict,Person)# Access the attributes of the Person objectprint(person.name)# Output: Johnprint(person.age)# Output: 30print(person.city)# Output: New YorkIn the above example, we define a dataclassPersonusing the@dataclassdecorator. ThePersondataclass has three attributes:name,age, andcity. We then have a dictionaryperson_dictrepresenting a person. By using thedecodefunction from dataclass_codec, we can easily convert the dictionary into a Person object. Finally, we access the attributes of the Person object and print their values.Advanced FeaturesNested DictionariesYou can use dataclass_codec to decode dictionaries that have nested dictionaries as values. The nested dictionaries will be decoded into nested dataclass objects.fromdataclassesimportdataclassfromdataclass_codecimportdecode# Define a nested dataclass@dataclassclassAddress:street:strcity:strzip_code:str# Define a dataclass with a nested dataclass@dataclassclassPerson:name:strage:intaddress:Address# Define a dictionary with a nested address dictionaryperson_dict={"name":"John","age":30,"address":{"street":"123 Main St","city":"New York","zip_code":"10001"}}# Decode the dictionary into a Person objectperson=decode(person_dict,Person)# Access the attributes of the Person object and its nested Address objectprint(person.name)# Output: Johnprint(person.age)# Output: 30print(person.address.street)# Output: 123 Main Stprint(person.address.city)# Output: New Yorkprint(person.address.zip_code)# Output: 10001In this example, we define a dataclassAddressrepresenting an address with attributesstreet,city, andzip_code. We also define a dataclassPersonwith attributesname,age, andaddress, whereaddressis an instance of theAddressdataclass. The dictionaryperson_dictcontains a nested dictionary for the address. By using thedecodefunction, we can easily convert the dictionary into a Person object with a nested Address object. Finally, we access the attributes of the Person object and its nested Address object and print their values.Remember to define all your dataclasses using the@dataclassdecorator for dataclass_codec to work correctly.Decoding a Dictionary with Generic ListfromdataclassesimportdataclassfromtypingimportList,TypeVarfromdataclass_codecimportdecode# Define a TypeVarT=TypeVar('T')# Define a generic dataclass@dataclassclassContainer:items:List[T]# Define a dictionary with a list of itemscontainer_dict={"items":[1,2,3,4,5]}# Decode the dictionary into a Container objectcontainer=decode(container_dict,Container[int])# Access the attributes of the Container objectprint(container.items)# Output: [1, 2, 3, 4, 5]In this example, we showcase how to decode a dictionary containing a list of generic types. We define a generic dataclassContainerwith a single attributeitems, which is a list of generic typeT. The dictionarycontainer_dictcontains a list of items[1, 2, 3, 4, 5]. By using thedecodefunction with the typeContainer[int], we can convert the dictionary into aContainerobject, where the list of items is preserved.Feel free to include this example in your readme to demonstrate how to decode a dictionary with a generic list into a corresponding dataclass object.Decode Context and Context Scope (ID:decode-context)Thedataclass_codeclibrary provides aDecodeContextclass and a context-based approach to manage the decoding behavior using thedecode_context_scopecontext manager.DecodeContext@dataclassclassDecodeContext:strict:bool=Falseprimitive_cast_values:bool=Truedataclass_unset_as_none:bool=Truecollect_errors:bool=FalseTheDecodeContextclass represents the decoding context with the following configurable options:strict(bool): If set toTrue, the decoder raises an exception when encountering unknown fields. Defaults toFalse.primitive_cast_values(bool): If set toTrue, the decoder attempts to cast values to their declared types. Defaults toTrue.dataclass_unset_as_none(bool): If set toTrue, the decoder treats unset fields in dataclasses asNone. Defaults toTrue.collect_errors(bool): If set toTrue, the decoder collects decoding errors as a list of(error_path, error)tuples. Defaults toFalse.decode_context_scope@contextmanagerdefdecode_context_scope(decode_context:DecodeContext,)->Generator[None,Any,None]:# Code for the context managerThedecode_context_scopeis a context manager that allows you to temporarily set a specificDecodeContextwithin a context block. This context manager ensures that the desired decoding behavior is applied within the block and reverts to the previous context afterward.Usage:withdecode_context_scope(DecodeContext(strict=True,primitive_cast_values=False)):# Perform decoding operations within this block# The specified decoding context will be in effectBy using thedecode_context_scopecontext manager, you can easily control the decoding behavior within a specific scope, allowing you to customize options such as strict decoding, casting values, handling unset fields, and collecting errors.Feel free to include this section in your readme to explain the usage ofDecodeContextanddecode_context_scopefor managing the decoding behavior within different contexts.Certainly! Here's an updated version of the section that includes a dataclass with a bytes property:Bytes Encoding and Decoding (ID:bytes-encoding-decoding)Thedataclass_codeclibrary provides built-in support for encoding and decoding byte data, including working with bytes properties within dataclasses. You can easily encode byte data into a string representation and decode it back into its original byte form. This is useful when working with binary data or when serializing and deserializing byte data in your applications.Encoding BytesTo encode byte data, you can use theencodefunction provided by thedataclass_codeclibrary. Theencodefunction takes a byte object as input and returns its string representation.Example:importbase64fromdataclassesimportdataclassfromdataclass_codecimportencode@dataclassclassMyData:binary_data:bytes# Create an instance of the dataclassmy_data=MyData(binary_data=b"Hello, world!")# Encode the byte dataencoded_data=encode(my_data)# Print the encoded dataprint(encoded_data)# Output: '{"binary_data": "SGVsbG8sIHdvcmxkIQ=="}'In this example, we define a dataclassMyDatawith abinary_dataproperty of typebytes. We create an instance of the dataclass and set thebinary_dataproperty tob"Hello, world!". We then use theencodefunction to encode the dataclass instance, including the byte data. The resulting encoded data is{"binary_data": "SGVsbG8sIHdvcmxkIQ=="}. The byte data is encoded using Base64 encoding within the JSON representation of the dataclass instance.Decoding BytesTo decode byte data back into its original form, you can use thedecodefunction provided by thedataclass_codeclibrary. Thedecodefunction takes the encoded data as a string and the target dataclass type and returns the decoded dataclass instance.Example:importbase64fromdataclassesimportdataclassfromdataclass_codecimportdecode@dataclassclassMyData:binary_data:bytes# Decode the encoded datadecoded_data=decode({"binary_data":"SGVsbG8sIHdvcmxkIQ=="},MyData)# Access the byte dataprint(decoded_data.binary_data)# Output: b"Hello, world!"In this example, we define the sameMyDatadataclass with abinary_dataproperty of typebytes. We use thedecodefunction to decode the encoded data{"binary_data": "SGVsbG8sIHdvcmxkIQ=="}back into its original dataclass form. The resulting decoded dataclass instance contains the byte datab"Hello, world!".By leveraging the encoding and decoding capabilities provided by thedataclass_codeclibrary, you can seamlessly work with byte data within dataclasses, ensuring efficient serialization and deserialization of binary data.Feel free to include this section in your readme to explain the process of encoding and decoding byte data, including working with bytes properties within dataclasses using thedataclass_codeclibrary.Conclusiondataclass_codec is a powerful library for decoding dictionaries into dataclasses in Python. It provides an easy and efficient way to convert data between Python objects and JSON-compatible formats. Whether you need to deserialize data for processing or manipulation purposes, dataclass_codec can simplify the process and save you time. Give it a try and see how it can enhance your data manipulation workflow.