Skip to content

Commit 6e580f1

Browse files
committed
reimplement to_dict
1 parent cd3d959 commit 6e580f1

File tree

2 files changed

+30
-35
lines changed

2 files changed

+30
-35
lines changed

moodle/utils/helper.py

Lines changed: 28 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,46 +7,41 @@
77
T = TypeVar("T")
88

99

10-
def to_dict(data: Any, name: str = "") -> Any:
10+
def to_dict(data: dict, name: str = "") -> dict:
1111
"""Properly format query string for webservice request
12+
The passed object itself must be a dict, but the returned value will be
13+
flattened to a dict with keys like `name[key]` or `name[index][key]`.
1214
1315
Args:
14-
data (Any): Query to be formated
16+
data (dict): Query to be formated
1517
name (str, optional): The key of the data. Defaults to "".
1618
1719
Returns:
18-
Any: Formated data
20+
dict: Formated data
1921
"""
20-
if not data:
21-
return data
22-
if isinstance(data, list):
23-
out = {}
24-
for idx, val in enumerate(data):
25-
val = to_dict(val)
26-
if isinstance(val, dict):
27-
for key, value in val.items():
28-
out[f"{name}[{idx}][{key}]"] = val[key]
29-
else:
30-
out_key = name
31-
# Check if data required name prefix
32-
if hasattr(data, "name"):
33-
out_key += f"[{getattr(data, 'name')}]"
34-
out_key += f"[{idx}]"
35-
out[out_key] = val
36-
return out
37-
if isinstance(data, dict):
38-
out = {}
39-
for key, value in data.items():
40-
if isinstance(value, list):
41-
out.update(to_dict(value, key))
42-
else:
43-
out[key] = value
44-
return out
45-
if has(data):
46-
return asdict_attr(data)
47-
if isinstance(data, datetime):
48-
return datetime.timestamp(data)
49-
return data
22+
23+
result = {}
24+
def inner(prefix: str, data: Any) -> dict:
25+
pairs = None
26+
if isinstance(data, list):
27+
pairs = enumerate(data)
28+
elif isinstance(data, dict):
29+
pairs = data.items()
30+
elif has(data):
31+
pairs = asdict_attr(data).items()
32+
33+
if pairs is not None:
34+
for key, value in pairs:
35+
inner(f"{prefix}[{key}]", value)
36+
else:
37+
if isinstance(data, datetime):
38+
data = datetime.timestamp(data)
39+
result[prefix] = data
40+
41+
for key, value in data.items():
42+
inner(key, value)
43+
44+
return result
5045

5146

5247
def fromtimestamp(d: str):

tests/test_utils/test_helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ class MyAttrClass:
4242
y = attr.ib()
4343

4444
# attr class
45-
result = to_dict(MyAttrClass(x=1, y=2))
46-
assert result == { 'x': 1, 'y': 2 }
45+
# result = to_dict(MyAttrClass(x=1, y=2))
46+
# assert result == { 'x': 1, 'y': 2 }
4747

4848
# dict with attr class
4949
result = to_dict(dict(a=MyAttrClass(x=1, y=2)))

0 commit comments

Comments
 (0)