1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
from dataclasses import dataclass
from typing import Generic, List, TypeVar, get_type_hints
from dacite import from_dict
T = TypeVar("T")
U = TypeVar("U")
@dataclass
class X:
a: str
@dataclass
class A(Generic[T, U]):
x: T
y: List[U]
def test_multi_generic():
data = {
"x": {
"a": "foo",
},
"y": [1, 2, 3],
}
result = from_dict(data_class=A[X, int], data=data)
assert result == A(x=X(a="foo"), y=[1, 2, 3])
# assert that the typing object hasn't been modified in-place
hints = get_type_hints(A)
assert hints["x"].__class__ is TypeVar
def test_generic_parent():
@dataclass
class B(A[X, int]):
z: str
data = {
"x": {
"a": "foo",
},
"y": [1, 2, 3],
"z": "bar",
}
result = from_dict(data_class=B, data=data)
assert result == B(x=X(a="foo"), y=[1, 2, 3], z="bar")
def test_generic_field():
@dataclass
class C:
z: A[X, int]
data = {
"z": {
"x": {
"a": "foo",
},
"y": [1, 2, 3],
}
}
result = from_dict(data_class=C, data=data)
assert result == C(z=A(x=X(a="foo"), y=[1, 2, 3]))
|