dataclasses-json
dataclasses-json copied to clipboard
`from_json` doesn't seem to recognize generic attributes
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?
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))
Target of #442