Skip to content
New issue

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

[FEATURE] ADT Support #539

Open
IlyaHalsky opened this issue Jul 24, 2024 · 0 comments
Open

[FEATURE] ADT Support #539

IlyaHalsky opened this issue Jul 24, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@IlyaHalsky
Copy link

IlyaHalsky commented Jul 24, 2024

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:

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').

Possible solution

Some kind of annotation for base class where I can register child types so it can handle from_dict and from_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:

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))

Context

No response

@IlyaHalsky IlyaHalsky added the enhancement New feature or request label Jul 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant