Project

General

Profile

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