How about add those attributes with a default value None
by using a metaclass
?
from dataclasses import dataclass
keys = ('id',
'name',
'pwd',
'picture',
'url',
'age')
class MyMeta(type):
def __call__(self, *args, **kwargs):
for p in keys:
kwargs[p] = kwargs.get(p)
cls_obj = self.__new__(self, *args, **kwargs)
self.__init__(cls_obj, *args, **kwargs)
return cls_obj
@dataclass
class User(metaclass=MyMeta):
id: str
name: str
pwd: str
picture: str
url: str
age: int
attributes1 = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "picture": None, "age": None, "url": "www.example.com"}
user1 = User(**attributes1)
print(user1)
attributes2 = {"id": "18ut2", "pwd": "qwerty", "name": "John Doe", "url": "www.example.com"} # No picture or age key anymore
user2 = User(**attributes2)
print(user2)