I have a JSON object that reads:
j = {"id": 1, "label": "x"}
I have two types:
class BaseModel:
def __init__(self, uuid):
self.uuid = uuid
class Entity(BaseModel):
def __init__(self, id, label):
super().__init__(id)
self.name = name
Note how id is stored as uuid in the BaseModel.
I can load Entity from the JSON object as:
entity = Entity(**j)
I want to re-write my model leveraging dataclass:
@dataclass
class BaseModel:
uuid = str
@dataclass
class Entity:
name = str
Since my JSON object does not have the uuid, entity = Entitye(**j) on the dataclass-based model will throw the following error:
TypeError: __init__() got an unexpected keyword argument 'id'
The "ugly" solutions I can think of:
Rename
idtouuidin JSON before initialization:j["uuid"] = j.pop("id")Define both
idanduuid:@dataclass class BaseModel: uuid = str @dataclass class Entity: id = str name = str # either use: uuid = id # or use this method def __post_init__(self): super().uuid = id
Is there any cleaner solution for this kind of object initialization in the dataclass realm?