Created
July 18, 2023 16:22
-
-
Save XFY9326/ae3963e80a189a508c7e2c2430953fb3 to your computer and use it in GitHub Desktop.
Example of using dataclass-json nested inheritance attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import dataclasses | |
import dataclasses_json | |
from dataclasses_json import DataClassJsonMixin | |
@dataclasses.dataclass(frozen=True) | |
class Value(DataClassJsonMixin): | |
value_type: str = dataclasses.field(init=False, default="unknown", metadata=dataclasses_json.config(field_name="type")) | |
@staticmethod | |
def value_decoder(content: any) -> 'Value': | |
if isinstance(content, dict) and "type" in content: | |
if content["type"] == "str": | |
return StringValue.from_dict(content) | |
elif content["type"] == "int": | |
return IntValue.from_dict(content) | |
elif content["type"] == "unknown": | |
return Value.from_dict(content) | |
raise NotImplementedError(f"Unknown value: {content}") | |
@dataclasses.dataclass(frozen=True) | |
class StringValue(Value, DataClassJsonMixin): | |
value: str | |
value_type: str = dataclasses.field(init=False, default="str", metadata=dataclasses_json.config(field_name="type")) | |
@dataclasses.dataclass(frozen=True) | |
class IntValue(Value, DataClassJsonMixin): | |
value: int | |
value_type: str = dataclasses.field(init=False, default="int", metadata=dataclasses_json.config(field_name="type")) | |
@dataclasses.dataclass(frozen=True) | |
class Data(DataClassJsonMixin): | |
name: str | |
value: Value = dataclasses.field(metadata=dataclasses_json.config(decoder=Value.value_decoder)) | |
if __name__ == '__main__': | |
obj_1 = Data( | |
name="data", | |
value=StringValue("text") | |
) | |
obj_2 = Data( | |
name="data", | |
value=IntValue(12345) | |
) | |
dict_1 = obj_1.to_dict() | |
dict_2 = obj_2.to_dict() | |
# {'name': 'data', 'value': {'type': 'str', 'value': 'text'}} | |
print(dict_1) | |
# {'name': 'data', 'value': {'type': 'int', 'value': 12345}} | |
print(dict_2) | |
# Data(name='data', value=StringValue(value_type='str', value='text')) | |
print(Data.from_dict(dict_1)) | |
# Data(name='data', value=IntValue(value_type='int', value=12345)) | |
print(Data.from_dict(dict_2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment