|
| 1 | +""" Defines interface contracts.""" |
| 2 | +import sys |
| 3 | + |
| 4 | + |
| 5 | +class Serializable: |
| 6 | + """ Serializable objects must implement a `toDict` method which |
| 7 | + converts the object properties to a Python dictionary whose |
| 8 | + keys are the named arguments to the class constructor. |
| 9 | + """ |
| 10 | + |
| 11 | + @classmethod |
| 12 | + def getMapping(cls): |
| 13 | + """ Returns the internal mapping dictionary for the class. |
| 14 | + You must implement this method to make classes serializable |
| 15 | + via `fromDict` and `toDict`. |
| 16 | + """ |
| 17 | + raise NotImplementedError(f"Object is not serializable. {cls.__name__} does not implement '_args'") |
| 18 | + |
| 19 | + @classmethod |
| 20 | + def fromDict(cls, options): |
| 21 | + """ Converts a Python Dictionary to the object using the object's constructor.""" |
| 22 | + internal_representation = options.copy() |
| 23 | + internal_representation.pop("kind") |
| 24 | + d = {} |
| 25 | + for key, value in internal_representation.items(): |
| 26 | + if isinstance(value, dict): |
| 27 | + c = value.get("kind") |
| 28 | + if dict in [type(i) for i in value.values()]: |
| 29 | + d[key] = getattr(sys.modules[__name__], c).fromDict(value) |
| 30 | + continue |
| 31 | + value.pop("kind") |
| 32 | + d[key] = getattr(sys.modules[__name__], c)(**value) |
| 33 | + continue |
| 34 | + d[key] = value |
| 35 | + return cls(**d) |
| 36 | + |
| 37 | + def toDict(self): |
| 38 | + """ Converts the object to a Python dictionary with the object's constructor arguments.""" |
| 39 | + args = self.getMapping() |
| 40 | + return {"kind": self.__class__.__name__, |
| 41 | + **{ |
| 42 | + public_key: getattr(self, internal_key).toDict() |
| 43 | + if isinstance(getattr(self, internal_key), Serializable) |
| 44 | + else getattr(self, internal_key) |
| 45 | + for public_key, internal_key in args.items() |
| 46 | + if hasattr(self, internal_key) and getattr(self, internal_key) is not None |
| 47 | + }} |
0 commit comments