Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Systematize ser/deser for all data structures #23

Open
hegdevinayi opened this issue Dec 7, 2021 · 0 comments
Open

Systematize ser/deser for all data structures #23

hegdevinayi opened this issue Dec 7, 2021 · 0 comments
Labels
enhancement New feature or request

Comments

@hegdevinayi
Copy link
Collaborator

hegdevinayi commented Dec 7, 2021

Most data structures, especially in the learning module, perform serialization (to JSON) and deserialization (from JSON) using custom, adhoc logic for each data structure/class. A systematic way to handle ser/deser in general would be to make all data structures in autocat inherit from a base Serializable class that implements generic ser/deser functionality.

Example (basic) Serializable class:

class Serializable(object):
    """Base abstract class for a serializable object."""

    def to_dict(self):
        """Convert and return object as dictionary."""
        keys = {k.lstrip("_") for k in vars(self)}
        attr = {k: Serializable._to_dict(self.__getattribute__(k)) for k in keys}
        return attr

    @staticmethod
    def _to_dict(obj):
        """Convert obj to a dictionary, and return it."""
        if isinstance(obj, list):
            return [Serializable._to_dict(i) for i in obj]
        elif hasattr(obj, "as_dict"):
            return obj.as_dict()
        else:
            return obj

    @classmethod
    def from_dict(cls, ddict):
        """Construct an object from the input dictionary."""
        return cls(**ddict)

and then autocat data structures need only to inherit from the Serializable class as follows:

class AutoCatDesignSpace(Serializable):
    ...
@hegdevinayi hegdevinayi added the enhancement New feature or request label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant