forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtomllib_w.py
More file actions
39 lines (33 loc) · 1.08 KB
/
Copy pathtomllib_w.py
File metadata and controls
39 lines (33 loc) · 1.08 KB
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
# tomllib_w.py
from datetime import date
def dumps(toml_dict, table=""):
def tables_at_end(item):
_, value = item
return isinstance(value, dict)
document = []
for key, value in sorted(toml_dict.items(), key=tables_at_end):
match value:
case dict():
table_key = f"{table}.{key}" if table else key
document.append(
f"\n[{table_key}]\n{dumps(value, table=table_key)}"
)
case _:
document.append(f"{key} = {_dumps_value(value)}")
return "\n".join(document)
def _dumps_value(value):
match value:
case bool():
return "true" if value else "false"
case float() | int():
return str(value)
case str():
return f'"{value}"'
case date():
return value.isoformat()
case list():
return "[" + ", ".join(_dumps_value(v) for v in value) + "]"
case _:
raise TypeError(
f"{type(value).__name__} {value!r} is not supported"
)