|
1
|
|
|
from typing import Any, List, TypeVar, Type, cast, Callable |
|
2
|
|
|
from enum import Enum |
|
3
|
|
|
from datetime import datetime, timedelta |
|
4
|
|
|
import dateutil.parser |
|
5
|
|
|
|
|
6
|
|
|
|
|
7
|
|
|
T = TypeVar("T") |
|
8
|
|
|
EnumT = TypeVar("EnumT", bound=Enum) |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
def from_str(x: Any) -> str: |
|
12
|
|
|
if x is None: |
|
13
|
|
|
return |
|
14
|
|
|
assert isinstance(x, str) |
|
15
|
|
|
return x |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
def from_bool(x: Any) -> bool: |
|
19
|
|
|
if x is None: |
|
20
|
|
|
return |
|
21
|
|
|
assert isinstance(x, bool) |
|
22
|
|
|
return x |
|
23
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
def from_int(x: Any) -> int: |
|
26
|
|
|
if x is None: |
|
27
|
|
|
return |
|
28
|
|
|
assert isinstance(x, int) and not isinstance(x, bool) |
|
29
|
|
|
return x |
|
30
|
|
|
|
|
31
|
|
|
|
|
32
|
|
|
def from_datetime(x: Any) -> datetime: |
|
33
|
|
|
if x is None: |
|
34
|
|
|
return |
|
35
|
|
|
return dateutil.parser.parse(x) |
|
36
|
|
|
|
|
37
|
|
|
# 'P0DT01H44M03.313433S' |
|
38
|
|
|
# using an iso 8601 lib to parse this seems like overkill |
|
39
|
|
|
|
|
40
|
|
|
|
|
41
|
|
|
def from_timedelta(x: Any) -> timedelta: |
|
42
|
|
|
if x is None: |
|
43
|
|
|
return |
|
44
|
|
|
return timedelta( |
|
45
|
|
|
hours=float(x[4:6]), minutes=float(x[7:9]), seconds=float(x[10:-1]) |
|
46
|
|
|
) |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
def from_none(x: Any) -> Any: |
|
50
|
|
|
assert x is None |
|
51
|
|
|
return x |
|
52
|
|
|
|
|
53
|
|
|
|
|
54
|
|
|
def to_class(c: Type[T], x: Any) -> dict: |
|
55
|
|
|
if x is None: |
|
56
|
|
|
return |
|
57
|
|
|
assert isinstance(x, c) |
|
58
|
|
|
return cast(Any, x).to_dict() |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
def from_list(f: Callable[[Any], T], x: Any) -> List[T]: |
|
62
|
|
|
if x is None: |
|
63
|
|
|
return |
|
64
|
|
|
assert isinstance(x, list) |
|
65
|
|
|
return [f(y) for y in x] |
|
66
|
|
|
|
|
67
|
|
|
|
|
68
|
|
|
def from_union(fs, x): |
|
69
|
|
|
for f in fs: |
|
70
|
|
|
try: |
|
71
|
|
|
return f(x) |
|
72
|
|
|
except Any: |
|
73
|
|
|
pass |
|
74
|
|
|
assert False |
|
75
|
|
|
|
|
76
|
|
|
|
|
77
|
|
|
def is_type(t: Type[T], x: Any) -> T: |
|
78
|
|
|
if x is None: |
|
79
|
|
|
return |
|
80
|
|
|
assert isinstance(x, t) |
|
81
|
|
|
return x |
|
82
|
|
|
|