forked from yukinarit/pyserde
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliteral.py
More file actions
43 lines (31 loc) · 828 Bytes
/
literal.py
File metadata and controls
43 lines (31 loc) · 828 Bytes
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
import sys
from dataclasses import dataclass
from serde.compat import SerdeError
if sys.version_info[:2] == (3, 7):
from typing_extensions import Literal
else:
from typing import Literal
from serde import serde
from serde.json import from_json, to_json
@serde
@dataclass
class Foo:
i: Literal[1, 2]
s: Literal["a", "b"]
def main():
f = Foo(1, "a")
print(f"Into Json: {to_json(f)}")
s = '{"i": 2, "s": "b"}'
print(f"From Json: {from_json(Foo, s)}")
try:
t = '{"i": 3, "s": "a"}'
from_json(Foo, t)
except SerdeError as err:
print(f"Cannot parse '{t}' as Foo: {err}")
try:
u = '{"i": 2, "s": "A"}'
from_json(Foo, u)
except SerdeError as err:
print(f"Cannot parse '{u}' as Foo: {err}")
if __name__ == '__main__':
main()