Project

General

Profile

1 11 aaronmk
# Useful functions and classes
2
3 931 aaronmk
#### Function wrappers for statements
4
5
def noop(*args, **kw_args): pass
6
7
def and_(a, b): return a and b
8
9 791 aaronmk
#### Object metadata
10
11 341 aaronmk
def type_name(value): return type(value).__name__
12
13 135 aaronmk
def module(value): return type(value).__module__.split('.')
14
15
def root_module(value): return module(value)[0]
16
17 791 aaronmk
#### Basic types
18
19
class ConstraintError(ValueError):
20
    def __init__(self, check_func, value):
21 795 aaronmk
        ValueError.__init__(self, str(value)+' must satisfy constraint '
22
            +check_func.__name__)
23 791 aaronmk
24 836 aaronmk
def cast(type_, val):
25
    '''Passes None through'''
26
    if val != None: val = type_(val)
27
    return val
28
29 791 aaronmk
def is_str(val): return isinstance(val, basestring)
30
31
#### Iterables
32
33 135 aaronmk
def first(iter_): return iter_.next()
34
35 133 aaronmk
def skip(iter_, func):
36
    # Advance iter while func is True
37
    try:
38
        while func(iter_.curr()): iter_.next()
39
    except StopIteration: pass # nothing after the matching elements
40
41 934 aaronmk
def list_subset(list_, idxs):
42
    subset = []
43
    for idx in idxs:
44
        try: subset.append(list_[idx])
45
        except IndexError: pass
46
    return subset
47
48 791 aaronmk
class CheckedIter:
49
    def __init__(self, check_func, iterable):
50
        self.check_func = check_func
51
        self.iter_ = iterable.__iter__()
52
53
    def __iter__(self): return self
54
55
    def next(self):
56
        entry = self.iter_.next()
57
        if self.check_func(entry): return entry
58
        else: raise ConstraintError(self.check_func, entry)
59
60
#### Dicts
61
62 330 aaronmk
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
63 466 aaronmk
64 467 aaronmk
def dict_subset(dict_, keys):
65
    subset = dict()
66
    for key in keys:
67
        try: subset[key] = dict_[key]
68
        except KeyError: pass
69
    return subset