We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
I'm not sure if this is even possible: I want to create summ type of dataclasses, which can be distinguished by some field:
class Base(DataClassJsonMixin): tpe: str @dataclass_json @dataclass class A(Base): field1: int tpe: str = 'a' @dataclass_json @dataclass class B(Base): field2: str tpe: str = 'b'
So that Base.from_json("""{"field1": 1, "tpe": "a"}""") would produce A(1, 'a').
Base.from_json("""{"field1": 1, "tpe": "a"}""")
A(1, 'a')
Some kind of annotation for base class where I can register child types so it can handle from_dict and from_json
from_dict
from_json
Scala's library Circe can do it by registering all classes in summ type or by pointing to the discriminator field circe-adt.
My current workaround looks like this:
all_types = [A,B] class BaseDecoder: types_map = {} for type_instance in all_types: types_map[type_instance.tpe] = type_instance @staticmethod def decode_dict(object_dict: dict) -> Base | None: if 'tpe' in object_dict and object_dict['tpe'] in BaseDecoder.types_map: decoder = BaseDecoder.types_map[object_dict['tpe']] return decoder.from_dict(object_dict) else: raise Exception(f"Unknown type {object_dict}") @dataclass_json @dataclass class Wrapper: value: Base = field(metadata=config(decoder=BaseDecoder.decode_dict))
No response
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Description
I'm not sure if this is even possible:
I want to create summ type of dataclasses, which can be distinguished by some field:
So that
Base.from_json("""{"field1": 1, "tpe": "a"}""")
would produceA(1, 'a')
.Possible solution
Some kind of annotation for base class where I can register child types so it can handle
from_dict
andfrom_json
Alternatives
Scala's library Circe can do it by registering all classes in summ type or by pointing to the discriminator field circe-adt.
My current workaround looks like this:
Context
No response
The text was updated successfully, but these errors were encountered: