1
|
# Useful functions and classes
|
2
|
|
3
|
import collections
|
4
|
|
5
|
#### Function wrappers for statements
|
6
|
|
7
|
def noop(*args, **kw_args): pass
|
8
|
|
9
|
def and_(a, b): return a and b
|
10
|
|
11
|
#### Object metadata
|
12
|
|
13
|
def type_name(value): return type(value).__name__
|
14
|
|
15
|
def module(value): return type(value).__module__.split('.')
|
16
|
|
17
|
def root_module(value): return module(value)[0]
|
18
|
|
19
|
#### Type checking and conversion
|
20
|
|
21
|
class ConstraintError(ValueError):
|
22
|
def __init__(self, check_func, value):
|
23
|
ValueError.__init__(self, str(value)+' must satisfy constraint '
|
24
|
+check_func.__name__)
|
25
|
|
26
|
def cast(type_, val):
|
27
|
'''Passes None through. Does not cast a subclass to a superclass (which
|
28
|
doesn't make sense in a dynamically-typed language).'''
|
29
|
if val != None and not isinstance(val, type_): val = type_(val)
|
30
|
return val
|
31
|
|
32
|
def all_not_none(vals): return reduce(and_, map(lambda v: v != None, vals))
|
33
|
|
34
|
def is_str(val): return isinstance(val, basestring)
|
35
|
|
36
|
def is_list(val): return isinstance(val, list)
|
37
|
|
38
|
def bool2str(val):
|
39
|
if val: return '1'
|
40
|
else: return ''
|
41
|
|
42
|
#### Basic types
|
43
|
|
44
|
def do_ignore_none(do, val):
|
45
|
if val == None: return val
|
46
|
else: return do(val)
|
47
|
|
48
|
def none_if(val, *none_vals):
|
49
|
for none_val in none_vals:
|
50
|
if cast(type(none_val), val) == none_val: return None
|
51
|
return val
|
52
|
|
53
|
#### Iterables
|
54
|
|
55
|
def first(iter_): return iter_.next()
|
56
|
|
57
|
def skip(iter_, func):
|
58
|
# Advance iter while func is True
|
59
|
try:
|
60
|
while func(iter_.curr()): iter_.next()
|
61
|
except StopIteration: pass # nothing after the matching elements
|
62
|
|
63
|
class WrapIter:
|
64
|
def __init__(self, wrap_func, iterable):
|
65
|
self.wrap_func = wrap_func
|
66
|
self.iter_ = iterable.__iter__()
|
67
|
|
68
|
def __iter__(self): return self
|
69
|
|
70
|
def next(self): return self.wrap_func(self.iter_.next())
|
71
|
|
72
|
class CheckedIter:
|
73
|
def __init__(self, check_func, iterable):
|
74
|
self.check_func = check_func
|
75
|
self.iter_ = iterable.__iter__()
|
76
|
|
77
|
def __iter__(self): return self
|
78
|
|
79
|
def next(self):
|
80
|
entry = self.iter_.next()
|
81
|
if self.check_func(entry): return entry
|
82
|
else: raise ConstraintError(self.check_func, entry)
|
83
|
|
84
|
#### Lists
|
85
|
|
86
|
def list_get(list_, idx, default=None):
|
87
|
try: return list_[idx]
|
88
|
except IndexError: return default
|
89
|
|
90
|
def list_set_length(list_, len_, fill=None, expand_only=False):
|
91
|
'''@param list_ Must be a list, not a tuple'''
|
92
|
extra_needed = len_ - len(list_)
|
93
|
if extra_needed > 0: list_ += extra_needed*[fill]
|
94
|
elif not expand_only: del list_[len_:]
|
95
|
|
96
|
def list_as_length(list_, len_, fill=None):
|
97
|
list_ = list(list_) # will also convert a tuple to a list
|
98
|
list_set_length(list_, len_, fill)
|
99
|
return list_
|
100
|
|
101
|
def list_set(list_, idx, value, default=None):
|
102
|
list_set_length(list_, idx+1, default, expand_only=True)
|
103
|
list_[idx] = value
|
104
|
|
105
|
def list_setdefault(list_, idx, default=None):
|
106
|
try: return list_[idx]
|
107
|
except IndexError:
|
108
|
list_set(list_, idx, default, default)
|
109
|
return default
|
110
|
|
111
|
def list_subset(list_, idxs):
|
112
|
subset = []
|
113
|
for idx in idxs:
|
114
|
try: subset.append(list_[idx])
|
115
|
except IndexError: pass
|
116
|
return subset
|
117
|
|
118
|
def list_eq_is(list0, list1):
|
119
|
'''Compares two lists using is'''
|
120
|
if len(list0) != len(list1): return False
|
121
|
for i in xrange(len(list0)):
|
122
|
if list0[i] is not list1[i]: return False
|
123
|
return True
|
124
|
|
125
|
def list_replace(list_, repl_elem, with_slice):
|
126
|
list_ = list_[:] # don't modify input!
|
127
|
while True:
|
128
|
try: idx = list_.index(repl_elem)
|
129
|
except ValueError: break
|
130
|
list_[idx:idx+1] = with_slice
|
131
|
return list_
|
132
|
|
133
|
def list_flip(list_): return dict((v, i) for i, v in enumerate(list_))
|
134
|
|
135
|
#### Dicts
|
136
|
|
137
|
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
|
138
|
|
139
|
def dict_subset(dict_, keys):
|
140
|
subset = dict()
|
141
|
for key in keys:
|
142
|
try: subset[key] = dict_[key]
|
143
|
except KeyError: pass
|
144
|
return subset
|
145
|
|
146
|
class DefaultDict(collections.defaultdict):
|
147
|
def __init__(self, dict_, default=None):
|
148
|
collections.defaultdict.__init__(self, lambda: default, dict_)
|
149
|
|
150
|
def dict_subset_right_join(dict_, keys):
|
151
|
'''Gets a subset of a dict, using None for subset keys that don't exist'''
|
152
|
return dict_subset(DefaultDict(dict_), keys)
|
153
|
|
154
|
class ListDict:
|
155
|
'''Views a list as a dict, given a key->index mapping
|
156
|
@pre len(list_) == len(keys)'''
|
157
|
def __init__(self, list_, keys, key_idxs=None):
|
158
|
assert len(list_) == len(keys)
|
159
|
if key_idxs == None: key_idxs = list_flip(keys)
|
160
|
self.list = list_
|
161
|
self.keys = keys
|
162
|
self.key_idxs = key_idxs
|
163
|
|
164
|
def __getitem__(self, key): return self.list[self.key_idxs[key]]
|
165
|
|
166
|
def __str__(self): return '{\n'+(''.join(str(k)+': '+str(v)+'\n'
|
167
|
for k, v in zip(self.keys, self.list)))+'}\n'
|