-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathutils.py
98 lines (79 loc) · 2.27 KB
/
utils.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import re
# We need a stable output to compare with expected patterns. But mark
# places where sorting is optional with 'maybesorted' so it can be
# optimized for "production" runs.
maybesorted = sorted
def pairwise(iterable, trailing=True):
"For sequence of (a, b, c) yield pairs of (a, b), (b, c), (c, None)."
prev = Ellipsis
for it in iterable:
if prev is not Ellipsis:
yield (prev, it)
prev = it
if trailing:
yield (it, None)
def make_set(v):
"Make set if not already."
if isinstance(v, set):
return v
return {v}
def set_union(*sets):
# Python's set.union is unfortunately not a class method,
# but a normal method, [and if used as unbound method],
# requires at least one argument (set).
if sets:
return set.union(*sets)
return set()
def set_intersection(*sets):
# Python's set.intersection is unfortunately not a class method,
# but a normal method, [and if used as unbound method],
# requires at least one argument (set).
if sets:
return set.intersection(*sets)
return set()
def natural_sort_key(s):
if not isinstance(s, str):
return s
arr = re.split("([0-9]+)", s)
return [int(x) if x.isdigit() else x for x in arr]
def repr_stable_dict(d):
res = "{"
comma = False
for k, v in sorted(d.items()):
if comma:
res += ", "
res += "%r: %r" % (k, v)
comma = True
res += "}"
return res
def repr_stable_set(d):
if not d:
return "set()"
res = "{"
comma = False
for k in sorted(list(d), key=lambda x: natural_sort_key(repr(x))):
if comma:
res += ", "
res += "%r" % (k,)
comma = True
res += "}"
return res
def repr_stable_seq(d):
res = "(" if isinstance(d, tuple) else "["
comma = False
for el in d:
if comma:
res += ", "
res += repr_stable(el)
comma = True
res += ")" if isinstance(d, tuple) else "]"
return res
def repr_stable(v):
if isinstance(v, dict):
return repr_stable_dict(v)
elif isinstance(v, (set, frozenset)):
return repr_stable_set(v)
elif isinstance(v, (list, tuple)):
return repr_stable_seq(v)
else:
return str(v)