I am calling a get_unit API that returns a json that contains info about a unit. The API supports sending a flag. For now let’s say the possible flags are basic, sensors, or last_update and depending on the flag, it returns data. I can provide multiple flags if I want
I want to read the json into a dataclass, but I don’t want to write a dataclass for each combination of flags. So my idea is to make a dataclass for each flag, and do “dynamic multiple inheritence” like mentioned in this question.
@dataclass
class SaUnitBasic(DataclassFromDict):
_id: str = field_from_dict(default="")
last_update: Union[dict, list, None] = field_from_dict(default_factory=list)
counters: Union[dict, list, None] = field_from_dict(default_factory=dict)
@dataclass
class SaUnitUpdates(DataclassFromDict):
_id: str = field_from_dict(default="")
counters: Union[dict, list, None] = field_from_dict(default_factory=dict)
@dataclass
class SaUnitSensors(DataclassFromDict):
_id: str = field_from_dict(default="")
sensors: Union[dict, list, None] = field_from_dict(default_factory=list)
As you can see, some basic fields are defined whatever the flag like _id, and some can exist in different flags like counters.
Instead of rewriting the member definition each time (because I might change the default behavior, for example), is there a way to store it in a variable and reuse it like this?
_id_VAR =(_id: str = field_from_dict(default=""))
counters_VAR = (counters: Union[dict, list, None] = field_from_dict(default_factory=dict))
@dataclass
class SaUnitBasic(DataclassFromDict):
_id_VAR
last_update: Union[dict, list, None] = field_from_dict(default_factory=list)
counters_VAR
@dataclass
class SaUnitUpdates(DataclassFromDict):
_id_VAR
counters_VAR
@dataclass
class SaUnitSensors(DataclassFromDict):
_id_VAR
sensors: Union[dict, list, None] = field_from_dict(default_factory=list)
I tried writing it as in the second example, but this is obviously wrong python syntax.
If you want to reuse a field, use a baseclass. So
_id_Var
should be define in a base class that all “flags” inherit from, andcounters_VAR
should be in a different baseclass that only some of the “flags” inherit from. But in general, this is honestly a very weird design.