Skip to content

Commit

Permalink
Address nested arrays case (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
barroco authored Oct 17, 2022
1 parent 175d223 commit b0244e1
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/implicitdict/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class MySubclass1(ImplicitDict):
>> '{"b": 2, "d": "foo", "a": 1}'
To deserialize JSON into an ImplicitDict subclass, use ImplicitDict.parse:
y: MySubclass1 = ImplicitDict.parse({'b': 2, 'd': 'foo', 'a': 1}, MySubclass1)
print(y.d)
>> foo
Expand Down Expand Up @@ -175,7 +175,9 @@ def _parse_value(value, value_type: Type):
# Type is generic
arg_types = get_args(value_type)
if generic_type is list:
if issubclass(arg_types[0], ImplicitDict):
if get_origin(arg_types[0]) is list:
return value
elif issubclass(arg_types[0], ImplicitDict):
# value is a list of some kind of ImplicitDict values
return [ImplicitDict.parse(item, arg_types[0]) for item in value]
else:
Expand Down
31 changes: 31 additions & 0 deletions tests/test_normal_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,16 @@ def test_features():

class NestedStructures(ImplicitDict):
my_list: List[MyData]
my_list_2: List[List[int]]
my_list_3: List[List[List[int]]]
my_dict: Dict[str, List[float]]


def test_nested_structures():
src_dict = {
'my_list': [{'foo': 'one'}, {'foo': 'two'}],
'my_list_2': [[1, 2], [3, 4, 5]],
'my_list_3': [[[1, 2, 3], [4, 5]], [[6], [7], [8]], [[9, 10]]],
'my_dict': {'foo': 1.23, 'bar': 4.56}
}
data: NestedStructures = ImplicitDict.parse(src_dict, NestedStructures)
Expand All @@ -121,6 +125,33 @@ def test_nested_structures():
assert data.my_list[0].foo == 'one'
assert data.my_list[1].foo == 'two'

assert len(data.my_list_2) == 2
assert len(data.my_list_2[0]) == 2
assert len(data.my_list_2[1]) == 3
assert data.my_list_2[0][0] == 1
assert data.my_list_2[0][1] == 2
assert data.my_list_2[1][0] == 3
assert data.my_list_2[1][1] == 4
assert data.my_list_2[1][2] == 5

assert len(data.my_list_3) == 3
assert len(data.my_list_3[0]) == 2
assert len(data.my_list_3[0][0]) == 3
assert len(data.my_list_3[0][1]) == 2
assert len(data.my_list_3[1]) == 3
assert len(data.my_list_3[2]) == 1
assert len(data.my_list_3[2][0]) == 2
assert data.my_list_3[0][0][0] == 1
assert data.my_list_3[0][0][1] == 2
assert data.my_list_3[0][0][2] == 3
assert data.my_list_3[0][1][0] == 4
assert data.my_list_3[0][1][1] == 5
assert data.my_list_3[1][0][0] == 6
assert data.my_list_3[1][1][0] == 7
assert data.my_list_3[1][2][0] == 8
assert data.my_list_3[2][0][0] == 9
assert data.my_list_3[2][0][1] == 10

assert len(data.my_dict) == 2
assert data.my_dict['foo'] == 1.23
assert data.my_dict['bar'] == 4.56

0 comments on commit b0244e1

Please sign in to comment.