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

from_json doesn't seem to recognize generic attributes #261

Open
fhennecker opened this issue Nov 12, 2020 · 2 comments
Open

from_json doesn't seem to recognize generic attributes #261

fhennecker opened this issue Nov 12, 2020 · 2 comments

Comments

@fhennecker
Copy link

fhennecker commented Nov 12, 2020

I tried adapting one example from the doc to generic dataclasses.

The following example fails to parse the Minions as such.

from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import TypeVar, Generic, List

T = TypeVar("T", str, int)


@dataclass_json
@dataclass(frozen=True)
class Minion(Generic[T]):
    name: T


@dataclass_json
@dataclass(frozen=True)
class Boss(Generic[T]):
    minions: List[Minion[T]]


boss = Boss([Minion("evil minion"), Minion("very evil minion")])

print(Boss.from_json(boss.to_json()))

This is the result, as you can see the minions are still dicts, not Minions

Boss(minion1={'name': 'evil minion'}, minion2={'name': 'very evil minion'})

Am I doing something wrong?

@fhennecker
Copy link
Author

fhennecker commented Nov 12, 2020

My current best workaround is to specify a decoder like this:

from dataclasses import dataclass, field
from dataclasses_json import dataclass_json, config

@dataclass_json
@dataclass(frozen=True)
class Boss(Generic[T]):
    minion: Minion[T] = field(metadata=config(decoder=Minion.from_dict))

@george-zubrienko
Copy link
Collaborator

Target of #442

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants