deepset-ai / canals

A component orchestration engine
https://deepset-ai.github.io/canals/
Apache License 2.0
27 stars 3 forks source link

Implement generic `default_to_dict` and `default_from_dict` #85

Closed silvanocerza closed 1 year ago

silvanocerza commented 1 year ago

Part of #84.

Add generic utility functions to ease serialization and deserialization of Components and other clasess. They are extremely similar to _default_component_to_dict and _default_component_from_dict but with no references to Component as they can be used for any class and object.

Example usage:

class MyClass:
    def __init__(self, my_param: int = 10):
        self.my_param = my_param

    def to_dict(self):
        return default_to_dict(self, my_param=self.my_param)

    @classmethod
    def from_dict(cls, data):
        return default_from_dict(cls, data)

obj = MyClass(my_param=1000)
data = obj.to_dict()
assert data == {
    "hash": 4378522336,
    "type": "MyClass",
    "init_parameters": {
        "my_param": 1000,
    },
}

data["init_parameters"]["my_param"] = 42
new_obj = MyClass.from_dict(data)
assert new_object.my_param == 42

This PR only adds them and their tests to keep it small. Further PRs will remove the default to_dict and from_dict added by the @component decorator.