Skip to content

Instantly share code, notes, and snippets.

@yashbhutoria
Last active February 7, 2020 18:39
Show Gist options
  • Save yashbhutoria/c05c60d34af0d91325d9217e6c218fed to your computer and use it in GitHub Desktop.
Save yashbhutoria/c05c60d34af0d91325d9217e6c218fed to your computer and use it in GitHub Desktop.
Metaclass to ease creation of DTOs and hook compatibility with json.loads for easy deserialization
class Dto(type):
def __new__(self,name,bases,at_dict,attributes):
at_dict["_properties"] = attributes
def init(self,**kwargs):
for _property in attributes:
received_value = kwargs.get(_property.name)
if received_value is not None:
if isinstance(received_value,_property.type):
self.__dict__[_property.name] = received_value
else:
raise TypeError(f'"{_property.name}" parameter is of wrong type.')
else:
raise ValueError(f'"{_property.name}" parameter is not received')
def rep(self):
return(str(self.__dict__))
@classmethod
def hook(cls,properties):
return cls(
**properties
)
at_dict["__init__"] = init
at_dict["__repr__"] = rep
at_dict["hook"] = hook
return type(
name,
bases,
at_dict
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment