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 135 aaronmk
def module(value): return type(value).__module__.split('.')
16
17
def root_module(value): return module(value)[0]
18
19 1233 aaronmk
#### Type checking and conversion
20 791 aaronmk
21
class ConstraintError(ValueError):
22
    def __init__(self, check_func, value):
23 795 aaronmk
        ValueError.__init__(self, str(value)+' must satisfy constraint '
24
            +check_func.__name__)
25 791 aaronmk
26 836 aaronmk
def cast(type_, val):
27 1046 aaronmk
    '''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 836 aaronmk
    return val
31
32 1233 aaronmk
def all_not_none(vals): return reduce(and_, map(lambda v: v != None, vals))
33
34 791 aaronmk
def is_str(val): return isinstance(val, basestring)
35
36 1007 aaronmk
def is_list(val): return isinstance(val, list)
37
38 1233 aaronmk
def bool2str(val):
39
    if val: return '1'
40
    else: return ''
41
42 1046 aaronmk
#### Basic types
43
44 1359 aaronmk
def do_ignore_none(do, val):
45
    if val == None: return val
46
    else: return do(val)
47
48 1373 aaronmk
def none_if(val, *none_vals):
49
    for none_val in none_vals:
50
        if cast(type(none_val), val) == none_val: return None
51
    return val
52 1046 aaronmk
53 1445 aaronmk
#### Classes
54
55
def classes_eq(val0, val1): return val0() == val1() # compare instances
56
57 791 aaronmk
#### Iterables
58
59 135 aaronmk
def first(iter_): return iter_.next()
60
61 133 aaronmk
def skip(iter_, func):
62
    # Advance iter while func is True
63
    try:
64
        while func(iter_.curr()): iter_.next()
65
    except StopIteration: pass # nothing after the matching elements
66
67 1147 aaronmk
class WrapIter:
68
    def __init__(self, wrap_func, iterable):
69
        self.wrap_func = wrap_func
70
        self.iter_ = iterable.__iter__()
71
72
    def __iter__(self): return self
73
74
    def next(self): return self.wrap_func(self.iter_.next())
75 934 aaronmk
76 791 aaronmk
class CheckedIter:
77
    def __init__(self, check_func, iterable):
78
        self.check_func = check_func
79
        self.iter_ = iterable.__iter__()
80
81
    def __iter__(self): return self
82
83
    def next(self):
84
        entry = self.iter_.next()
85
        if self.check_func(entry): return entry
86
        else: raise ConstraintError(self.check_func, entry)
87
88 1008 aaronmk
#### Lists
89
90
def list_get(list_, idx, default=None):
91
    try: return list_[idx]
92
    except IndexError: return default
93
94 1414 aaronmk
def list_set_length(list_, len_, fill=None, expand_only=False):
95 1415 aaronmk
    '''@param list_ Must be a list, not a tuple'''
96 1414 aaronmk
    extra_needed = len_ - len(list_)
97
    if extra_needed > 0: list_ += extra_needed*[fill]
98
    elif not expand_only: del list_[len_:]
99
100 1415 aaronmk
def list_as_length(list_, len_, fill=None):
101
    list_ = list(list_) # will also convert a tuple to a list
102
    list_set_length(list_, len_, fill)
103
    return list_
104
105 1281 aaronmk
def list_set(list_, idx, value, default=None):
106 1414 aaronmk
    list_set_length(list_, idx+1, default, expand_only=True)
107 1281 aaronmk
    list_[idx] = value
108
109
def list_setdefault(list_, idx, default=None):
110
    try: return list_[idx]
111
    except IndexError:
112
        list_set(list_, idx, default, default)
113
        return default
114
115 1147 aaronmk
def list_subset(list_, idxs):
116
    subset = []
117
    for idx in idxs:
118
        try: subset.append(list_[idx])
119
        except IndexError: pass
120
    return subset
121
122 1012 aaronmk
def list_eq_is(list0, list1):
123
    '''Compares two lists using is'''
124
    if len(list0) != len(list1): return False
125
    for i in xrange(len(list0)):
126
        if list0[i] is not list1[i]: return False
127
    return True
128
129 1344 aaronmk
def list_replace(list_, repl_elem, with_slice):
130
    list_ = list_[:] # don't modify input!
131
    while True:
132
        try: idx = list_.index(repl_elem)
133
        except ValueError: break
134
        list_[idx:idx+1] = with_slice
135
    return list_
136
137 1145 aaronmk
def list_flip(list_): return dict((v, i) for i, v in enumerate(list_))
138
139 791 aaronmk
#### Dicts
140
141 330 aaronmk
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
142 466 aaronmk
143 467 aaronmk
def dict_subset(dict_, keys):
144
    subset = dict()
145
    for key in keys:
146
        try: subset[key] = dict_[key]
147
        except KeyError: pass
148
    return subset
149 1068 aaronmk
150
class DefaultDict(collections.defaultdict):
151
    def __init__(self, dict_, default=None):
152
        collections.defaultdict.__init__(self, lambda: default, dict_)
153
154
def dict_subset_right_join(dict_, keys):
155
    '''Gets a subset of a dict, using None for subset keys that don't exist'''
156
    return dict_subset(DefaultDict(dict_), keys)
157 1147 aaronmk
158
class ListDict:
159 1415 aaronmk
    '''Views a list as a dict, given a key->index mapping
160
    @pre len(list_) == len(keys)'''
161 1147 aaronmk
    def __init__(self, list_, keys, key_idxs=None):
162 1415 aaronmk
        assert len(list_) == len(keys)
163 1147 aaronmk
        if key_idxs == None: key_idxs = list_flip(keys)
164
        self.list = list_
165
        self.keys = keys
166
        self.key_idxs = key_idxs
167
168
    def __getitem__(self, key): return self.list[self.key_idxs[key]]
169
170 1178 aaronmk
    def __str__(self): return '{\n'+(''.join(str(k)+': '+str(v)+'\n'
171
        for k, v in zip(self.keys, self.list)))+'}\n'
172 1443 aaronmk
173
#### Named tuples
174
175
class NamedTuple:
176
    def __init__(self, **attrs): self.__dict__ = attrs