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 coalesce(*vals):
|
49
|
for val in vals:
|
50
|
if val != None: return val
|
51
|
return None
|
52
|
|
53
|
def none_if(val, *none_vals):
|
54
|
for none_val in none_vals:
|
55
|
if cast(type(none_val), val) == none_val: return None
|
56
|
return val
|
57
|
|
58
|
#### Classes
|
59
|
|
60
|
def classes_eq(val0, val1): return val0() == val1() # compare instances
|
61
|
|
62
|
#### Iterables
|
63
|
|
64
|
def first(iter_): return iter_.next()
|
65
|
|
66
|
def skip(iter_, func):
|
67
|
# Advance iter while func is True
|
68
|
try:
|
69
|
while func(iter_.curr()): iter_.next()
|
70
|
except StopIteration: pass # nothing after the matching elements
|
71
|
|
72
|
class WrapIter:
|
73
|
def __init__(self, wrap_func, iterable):
|
74
|
self.wrap_func = wrap_func
|
75
|
self.iter_ = iterable.__iter__()
|
76
|
|
77
|
def __iter__(self): return self
|
78
|
|
79
|
def next(self): return self.wrap_func(self.iter_.next())
|
80
|
|
81
|
class CheckedIter:
|
82
|
def __init__(self, check_func, iterable):
|
83
|
self.check_func = check_func
|
84
|
self.iter_ = iterable.__iter__()
|
85
|
|
86
|
def __iter__(self): return self
|
87
|
|
88
|
def next(self):
|
89
|
entry = self.iter_.next()
|
90
|
if self.check_func(entry): return entry
|
91
|
else: raise ConstraintError(self.check_func, entry)
|
92
|
|
93
|
#### Lists
|
94
|
|
95
|
def list_get(list_, idx, default=None):
|
96
|
try: return list_[idx]
|
97
|
except IndexError: return default
|
98
|
|
99
|
def list_set_length(list_, len_, fill=None, expand_only=False):
|
100
|
'''@param list_ Must be a list, not a tuple'''
|
101
|
extra_needed = len_ - len(list_)
|
102
|
if extra_needed > 0: list_ += extra_needed*[fill]
|
103
|
elif not expand_only: del list_[len_:]
|
104
|
|
105
|
def list_as_length(list_, len_, fill=None):
|
106
|
list_ = list(list_) # will also convert a tuple to a list
|
107
|
list_set_length(list_, len_, fill)
|
108
|
return list_
|
109
|
|
110
|
def list_set(list_, idx, value, default=None):
|
111
|
list_set_length(list_, idx+1, default, expand_only=True)
|
112
|
list_[idx] = value
|
113
|
|
114
|
def list_setdefault(list_, idx, default=None):
|
115
|
try: return list_[idx]
|
116
|
except IndexError:
|
117
|
list_set(list_, idx, default, default)
|
118
|
return default
|
119
|
|
120
|
subset_skip = object() # tells list_subset() to leave out invalid indexes
|
121
|
|
122
|
def list_subset(list_, idxs, default=subset_skip):
|
123
|
'''
|
124
|
@param idxs list|None If None, returns entire list
|
125
|
@param default The value to use for invalid indexes, or subset_skip to leave
|
126
|
them out of the returned list
|
127
|
'''
|
128
|
if idxs == None: return list_
|
129
|
subset = []
|
130
|
for idx in idxs:
|
131
|
value = list_get(list_, idx, default)
|
132
|
if value is not subset_skip: subset.append(value)
|
133
|
return subset
|
134
|
|
135
|
def list_eq_is(list0, list1):
|
136
|
'''Compares two lists using is'''
|
137
|
if len(list0) != len(list1): return False
|
138
|
for i in xrange(len(list0)):
|
139
|
if list0[i] is not list1[i]: return False
|
140
|
return True
|
141
|
|
142
|
def list_replace(list_, repl_elem, with_slice):
|
143
|
list_ = list_[:] # don't modify input!
|
144
|
while True:
|
145
|
try: idx = list_.index(repl_elem)
|
146
|
except ValueError: break
|
147
|
list_[idx:idx+1] = with_slice
|
148
|
return list_
|
149
|
|
150
|
def list_flip(list_): return dict((v, i) for i, v in enumerate(list_))
|
151
|
|
152
|
def sort_by_len(list_of_lists): list_of_lists.sort(lambda *a: cmp(*map(len, a)))
|
153
|
|
154
|
def shortest(*lists):
|
155
|
lists = list(lists)
|
156
|
sort_by_len(lists)
|
157
|
return lists[0]
|
158
|
|
159
|
def longest(*lists):
|
160
|
lists = list(lists)
|
161
|
sort_by_len(lists)
|
162
|
return lists[-1]
|
163
|
|
164
|
def all_equal(vals, default=False):
|
165
|
'''@return default if len(vals) < 2'''
|
166
|
if len(vals) < 2: return default
|
167
|
return reduce(and_, map(lambda v: v == vals[0], vals), True)
|
168
|
|
169
|
def all_equal_ignore_none(vals):
|
170
|
return all_equal(filter(lambda v: v != None, vals), default=False)
|
171
|
|
172
|
#### Dicts
|
173
|
|
174
|
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
|
175
|
|
176
|
def dict_subset(dict_, keys):
|
177
|
subset = dict()
|
178
|
for key in keys:
|
179
|
try: subset[key] = dict_[key]
|
180
|
except KeyError: pass
|
181
|
return subset
|
182
|
|
183
|
def have_same_value(dict_, *keys):
|
184
|
return all_equal_ignore_none([dict_.get(k, None) for k in keys])
|
185
|
|
186
|
class DefaultDict(collections.defaultdict):
|
187
|
def __init__(self, dict_, default=None):
|
188
|
collections.defaultdict.__init__(self, lambda: default, dict_)
|
189
|
|
190
|
def dict_subset_right_join(dict_, keys):
|
191
|
'''Gets a subset of a dict, using None for subset keys that don't exist'''
|
192
|
return dict_subset(DefaultDict(dict_), keys)
|
193
|
|
194
|
class ListDict:
|
195
|
'''Views a list as a dict, given a key->index mapping
|
196
|
@pre len(list_) == len(keys)'''
|
197
|
def __init__(self, list_, keys, key_idxs=None):
|
198
|
assert len(list_) == len(keys)
|
199
|
if key_idxs == None: key_idxs = list_flip(keys)
|
200
|
self.list = list_
|
201
|
self.keys = keys
|
202
|
self.key_idxs = key_idxs
|
203
|
|
204
|
def __getitem__(self, key): return self.list[self.key_idxs[key]]
|
205
|
|
206
|
def __str__(self): return '{\n'+(''.join(str(k)+': '+str(v)+'\n'
|
207
|
for k, v in zip(self.keys, self.list)))+'}\n'
|
208
|
|
209
|
#### Named tuples
|
210
|
|
211
|
class NamedTuple:
|
212
|
def __init__(self, **attrs): self.__dict__ = attrs
|
213
|
|
214
|
def __iter__(self): return iter(self.__dict__)
|
215
|
|
216
|
def __getitem__(self, key): return getattr(self, key)
|