Project

General

Profile

1
# Useful functions and classes
2

    
3
import objects
4

    
5
import collections
6

    
7
#### Function wrappers for statements
8

    
9
def noop(*args, **kw_args): pass
10

    
11
def and_(a, b): return a and b
12

    
13
#### Object metadata
14

    
15
def type_name(value): return type(value).__name__
16

    
17
def class_name(value): return value.__class__.__name__
18

    
19
def module(value): return type(value).__module__.split('.')
20

    
21
def root_module(value): return module(value)[0]
22

    
23
#### Type checking and conversion
24

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

    
30
def cast(type_, val):
31
    '''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
    return val
35

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

    
38
def is_str(val): return isinstance(val, basestring)
39

    
40
def is_list(val): return isinstance(val, list)
41

    
42
def bool2str(val):
43
    if val: return '1'
44
    else: return ''
45

    
46
#### Basic types
47

    
48
def do_ignore_none(do, val):
49
    if val == None: return val
50
    else: return do(val)
51

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

    
57
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

    
62
#### Classes
63

    
64
def classes_eq(val0, val1): return val0() == val1() # compare instances
65

    
66
#### Iterables
67

    
68
def first(iter_): return iter_.next()
69

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

    
85
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
#### Lists
98

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

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

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

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

    
156
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
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
#### Dicts
177

    
178
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
179

    
180
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

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

    
190
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

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

    
213
#### Named tuples
214

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