dataclasses-json icon indicating copy to clipboard operation
dataclasses-json copied to clipboard

How to handle Generic type?

Open itaied246 opened this issue 2 years ago • 3 comments

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.

itaied246 avatar Nov 15 '21 07:11 itaied246

any answer on this?

natilivni avatar May 12 '22 09:05 natilivni

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]?

lidatong avatar May 12 '22 12:05 lidatong

Should be ClassA[ClassB].from_json?

george-zubrienko avatar Jul 20 '23 22:07 george-zubrienko