Project

General

Profile

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 class_name(value): return value.__class__.__name__
16

    
17
def module(value): return type(value).__module__.split('.')
18

    
19
def root_module(value): return module(value)[0]
20

    
21
#### Type checking and conversion
22

    
23
class ConstraintError(ValueError):
24
    def __init__(self, check_func, value):
25
        ValueError.__init__(self, str(value)+' must satisfy constraint '
26
            +check_func.__name__)
27

    
28
def cast(type_, val):
29
    '''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
    return val
33

    
34
def all_not_none(vals): return reduce(and_, map(lambda v: v != None, vals))
35

    
36
def is_str(val): return isinstance(val, basestring)
37

    
38
def is_list(val): return isinstance(val, list)
39

    
40
def bool2str(val):
41
    if val: return '1'
42
    else: return ''
43

    
44
#### Basic types
45

    
46
def do_ignore_none(do, val):
47
    if val == None: return val
48
    else: return do(val)
49

    
50
def coalesce(*vals):
51
    for val in vals:
52
        if val != None: return val
53
    return None
54

    
55
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

    
60
#### Classes
61

    
62
def classes_eq(val0, val1): return val0() == val1() # compare instances
63

    
64
#### Iterables
65

    
66
def first(iter_): return iter_.next()
67

    
68
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
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

    
83
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
#### Lists
96

    
97
def list_get(list_, idx, default=None):
98
    try: return list_[idx]
99
    except IndexError: return default
100

    
101
def list_set_length(list_, len_, fill=None, expand_only=False):
102
    '''@param list_ Must be a list, not a tuple'''
103
    extra_needed = len_ - len(list_)
104
    if extra_needed > 0: list_ += extra_needed*[fill]
105
    elif not expand_only: del list_[len_:]
106

    
107
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
def list_set(list_, idx, value, default=None):
113
    list_set_length(list_, idx+1, default, expand_only=True)
114
    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
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
    if idxs == None: return list_
131
    subset = []
132
    for idx in idxs:
133
        value = list_get(list_, idx, default)
134
        if value is not subset_skip: subset.append(value)
135
    return subset
136

    
137
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
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
def list_flip(list_): return dict((v, i) for i, v in enumerate(list_))
153

    
154
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
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
#### Dicts
175

    
176
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
177

    
178
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

    
185
def have_same_value(dict_, *keys):
186
    return all_equal_ignore_none([dict_.get(k, None) for k in keys])
187

    
188
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

    
196
class ListDict:
197
    '''Views a list as a dict, given a key->index mapping
198
    @pre len(list_) == len(keys)'''
199
    def __init__(self, list_, keys, key_idxs=None):
200
        assert len(list_) == len(keys)
201
        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
    def __str__(self): return '{\n'+(''.join(str(k)+': '+str(v)+'\n'
209
        for k, v in zip(self.keys, self.list)))+'}\n'
210

    
211
#### Named tuples
212

    
213
class NamedTuple:
214
    def __init__(self, **attrs): self.__dict__ = attrs
215
    
216
    def __iter__(self): return iter(self.__dict__)
217
    
218
    def __getitem__(self, key): return getattr(self, key)
(30-30/35)