-
Notifications
You must be signed in to change notification settings - Fork 0
/
serializer.py
52 lines (45 loc) · 1.88 KB
/
serializer.py
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
from uontypes.uon_value import UonValue
from uontypes.uon_user_type import UonUserType
def python_to_uon(input_):
"""Convert an input to uon. If the input is a Uon Python object,
instance of <Uon> type, just return the string representation which
is the equivalent representation in UON format.
Otherwise if it is a Python built-in type, convert it to its closest
equivalent in Uon. For numeric types precision is by default 64. For
container types, the function is called recursively on its content.
No support for remaining built-in types, especially bytes, since Uon
has its own binary interpretation.
Args:
input_ (object): the Python object to serialize to uon
"""
# TODO: check if uon type in general
if isinstance(input_, UonValue) or isinstance(input_, UonUserType):
return str(input_)
elif isinstance(input_, dict):
dict_to_uon = {}
for k, v in input_.items():
if not isinstance(k, str):
raise UonSerializerError("Uon dictionary keys must be "
"hashable strings.")
dict_to_uon[k] = python_to_uon(v)
return ("{"
+ ", ".join("{}: {}"
.format(k, v) for k, v in dict_to_uon.items())
+ "}")
elif isinstance(input_, list):
return "[" + ", ".join(list(map(python_to_uon, input_))) + "]"
elif isinstance(input_, int):
return f"!int64 {input_}"
elif isinstance(input_, float):
return f"!float64 {input_}"
elif isinstance(input_, str):
return f"!str {input_}"
elif isinstance(input_, bool):
bool_result = "true" if input_ else "false"
return f"!bool {bool_result}"
elif input_ is None:
return "null"
else:
raise ValueError("Unsupported type")
class UonSerializerError(Exception):
pass