Project

General

Profile

1 11 aaronmk
# Useful functions and classes
2
3 1068 aaronmk
import collections
4
5 931 aaronmk
#### Function wrappers for statements
6
7
def noop(*args, **kw_args): pass
8
9
def and_(a, b): return a and b
10
11 791 aaronmk
#### Object metadata
12
13 341 aaronmk
def type_name(value): return type(value).__name__
14
15 2299 aaronmk
def class_name(value): return value.__class__.__name__
16
17 135 aaronmk
def module(value): return type(value).__module__.split('.')
18
19
def root_module(value): return module(value)[0]
20
21 1233 aaronmk
#### Type checking and conversion
22 791 aaronmk
23
class ConstraintError(ValueError):
24
    def __init__(self, check_func, value):
25 795 aaronmk
        ValueError.__init__(self, str(value)+' must satisfy constraint '
26
            +check_func.__name__)
27 791 aaronmk
28 836 aaronmk
def cast(type_, val):
29 1046 aaronmk
    '''Passes None through. Does not cast a subclass to a superclass (which
30
    doesn't make sense in a dynamically-typed language).'''
31
    if val != None and not isinstance(val, type_): val = type_(val)
32 836 aaronmk
    return val
33
34 1233 aaronmk
def all_not_none(vals): return reduce(and_, map(lambda v: v != None, vals))
35
36 791 aaronmk
def is_str(val): return isinstance(val, basestring)
37
38 1007 aaronmk
def is_list(val): return isinstance(val, list)
39
40 1233 aaronmk
def bool2str(val):
41
    if val: return '1'
42
    else: return ''
43
44 1046 aaronmk
#### Basic types
45
46 1359 aaronmk
def do_ignore_none(do, val):
47
    if val == None: return val
48
    else: return do(val)
49
50 1483 aaronmk
def coalesce(*vals):
51
    for val in vals:
52
        if val != None: return val
53
    return None
54
55 1373 aaronmk
def none_if(val, *none_vals):
56
    for none_val in none_vals:
57
        if cast(type(none_val), val) == none_val: return None
58
    return val
59 1046 aaronmk
60 1445 aaronmk
#### Classes
61
62
def classes_eq(val0, val1): return val0() == val1() # compare instances
63
64 791 aaronmk
#### Iterables
65
66 135 aaronmk
def first(iter_): return iter_.next()
67
68 133 aaronmk
def skip(iter_, func):
69
    # Advance iter while func is True
70
    try:
71
        while func(iter_.curr()): iter_.next()
72
    except StopIteration: pass # nothing after the matching elements
73
74 1147 aaronmk
class WrapIter:
75
    def __init__(self, wrap_func, iterable):
76
        self.wrap_func = wrap_func
77
        self.iter_ = iterable.__iter__()
78
79
    def __iter__(self): return self
80
81
    def next(self): return self.wrap_func(self.iter_.next())
82 934 aaronmk
83 791 aaronmk
class CheckedIter:
84
    def __init__(self, check_func, iterable):
85
        self.check_func = check_func
86
        self.iter_ = iterable.__iter__()
87
88
    def __iter__(self): return self
89
90
    def next(self):
91
        entry = self.iter_.next()
92
        if self.check_func(entry): return entry
93
        else: raise ConstraintError(self.check_func, entry)
94
95 1008 aaronmk
#### Lists
96
97
def list_get(list_, idx, default=None):
98
    try: return list_[idx]
99
    except IndexError: return default
100
101 1414 aaronmk
def list_set_length(list_, len_, fill=None, expand_only=False):
102 1415 aaronmk
    '''@param list_ Must be a list, not a tuple'''
103 1414 aaronmk
    extra_needed = len_ - len(list_)
104
    if extra_needed > 0: list_ += extra_needed*[fill]
105
    elif not expand_only: del list_[len_:]
106
107 1415 aaronmk
def list_as_length(list_, len_, fill=None):
108
    list_ = list(list_) # will also convert a tuple to a list
109
    list_set_length(list_, len_, fill)
110
    return list_
111
112 1281 aaronmk
def list_set(list_, idx, value, default=None):
113 1414 aaronmk
    list_set_length(list_, idx+1, default, expand_only=True)
114 1281 aaronmk
    list_[idx] = value
115
116
def list_setdefault(list_, idx, default=None):
117
    try: return list_[idx]
118
    except IndexError:
119
        list_set(list_, idx, default, default)
120
        return default
121
122 2020 aaronmk
subset_skip = object() # tells list_subset() to leave out invalid indexes
123
124
def list_subset(list_, idxs, default=subset_skip):
125
    '''
126
    @param idxs list|None If None, returns entire list
127
    @param default The value to use for invalid indexes, or subset_skip to leave
128
        them out of the returned list
129
    '''
130 1494 aaronmk
    if idxs == None: return list_
131 1147 aaronmk
    subset = []
132
    for idx in idxs:
133 2020 aaronmk
        value = list_get(list_, idx, default)
134 2254 aaronmk
        if value is not subset_skip: subset.append(value)
135 1147 aaronmk
    return subset
136
137 1012 aaronmk
def list_eq_is(list0, list1):
138
    '''Compares two lists using is'''
139
    if len(list0) != len(list1): return False
140
    for i in xrange(len(list0)):
141
        if list0[i] is not list1[i]: return False
142
    return True
143
144 1344 aaronmk
def list_replace(list_, repl_elem, with_slice):
145
    list_ = list_[:] # don't modify input!
146
    while True:
147
        try: idx = list_.index(repl_elem)
148
        except ValueError: break
149
        list_[idx:idx+1] = with_slice
150
    return list_
151
152 1145 aaronmk
def list_flip(list_): return dict((v, i) for i, v in enumerate(list_))
153
154 1767 aaronmk
def sort_by_len(list_of_lists): list_of_lists.sort(lambda *a: cmp(*map(len, a)))
155
156
def shortest(*lists):
157
    lists = list(lists)
158
    sort_by_len(lists)
159
    return lists[0]
160
161
def longest(*lists):
162
    lists = list(lists)
163
    sort_by_len(lists)
164
    return lists[-1]
165
166 1785 aaronmk
def all_equal(vals, default=False):
167
    '''@return default if len(vals) < 2'''
168
    if len(vals) < 2: return default
169
    return reduce(and_, map(lambda v: v == vals[0], vals), True)
170
171
def all_equal_ignore_none(vals):
172
    return all_equal(filter(lambda v: v != None, vals), default=False)
173
174 791 aaronmk
#### Dicts
175
176 330 aaronmk
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
177 466 aaronmk
178 467 aaronmk
def dict_subset(dict_, keys):
179
    subset = dict()
180
    for key in keys:
181
        try: subset[key] = dict_[key]
182
        except KeyError: pass
183
    return subset
184 1068 aaronmk
185 1785 aaronmk
def have_same_value(dict_, *keys):
186
    return all_equal_ignore_none([dict_.get(k, None) for k in keys])
187
188 1068 aaronmk
class DefaultDict(collections.defaultdict):
189
    def __init__(self, dict_, default=None):
190
        collections.defaultdict.__init__(self, lambda: default, dict_)
191
192
def dict_subset_right_join(dict_, keys):
193
    '''Gets a subset of a dict, using None for subset keys that don't exist'''
194
    return dict_subset(DefaultDict(dict_), keys)
195 1147 aaronmk
196
class ListDict:
197 1415 aaronmk
    '''Views a list as a dict, given a key->index mapping
198
    @pre len(list_) == len(keys)'''
199 1147 aaronmk
    def __init__(self, list_, keys, key_idxs=None):
200 1415 aaronmk
        assert len(list_) == len(keys)
201 1147 aaronmk
        if key_idxs == None: key_idxs = list_flip(keys)
202
        self.list = list_
203
        self.keys = keys
204
        self.key_idxs = key_idxs
205
206
    def __getitem__(self, key): return self.list[self.key_idxs[key]]
207
208 1178 aaronmk
    def __str__(self): return '{\n'+(''.join(str(k)+': '+str(v)+'\n'
209
        for k, v in zip(self.keys, self.list)))+'}\n'
210 1443 aaronmk
211
#### Named tuples
212
213
class NamedTuple:
214
    def __init__(self, **attrs): self.__dict__ = attrs
215 1908 aaronmk
216 1910 aaronmk
    def __iter__(self): return iter(self.__dict__)
217 1908 aaronmk
218
    def __getitem__(self, key): return getattr(self, key)