dataclasses-json
dataclasses-json copied to clipboard
How to handle Generic type?
I have this problem with Generic
types:
from typing import Generic, TypeVar
T = TypeVar("T")
@dataclass_json
@dataclass
class ClassB:
name: str
@dataclass_json
@dataclass
class ClassA(Generic[T]):
data: T
ClassA.from_json(ClassA(data=ClassB(name="name")).to_json())
# actual: ClassA(data={'name': 'name'})
# expected: ClassA(data=ClassB(name="name")
How can I tell from_json
to treat the Generic
as ClassB
?
Please consider that I have a single ClassA
, but multiple and different classes like ClassB
, but at the time of parsing, I know the Generic's type class.
any answer on this?
How can I tell from_json to treat the Generic as ClassB?
i just tried, and your example should successfully .from_json
at runtime. or are you talking about static typing
checks? if so, what's the error? can you explicitly annotate x: ClassA[ClassB]
?
Should be ClassA[ClassB].from_json
?