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 1007 aaronmk
#### Type checking
18 791 aaronmk
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 1046 aaronmk
    '''Passes None through. Does not cast a subclass to a superclass (which
26
    doesn't make sense in a dynamically-typed language).'''
27
    if val != None and not isinstance(val, type_): val = type_(val)
28 836 aaronmk
    return val
29
30 791 aaronmk
def is_str(val): return isinstance(val, basestring)
31
32 1007 aaronmk
def is_list(val): return isinstance(val, list)
33
34 1046 aaronmk
#### Basic types
35
36
def none_if(val, none_val):
37
    if cast(type(none_val), val) == none_val: return None
38
    else: return val
39
40 791 aaronmk
#### Iterables
41
42 135 aaronmk
def first(iter_): return iter_.next()
43
44 133 aaronmk
def skip(iter_, func):
45
    # Advance iter while func is True
46
    try:
47
        while func(iter_.curr()): iter_.next()
48
    except StopIteration: pass # nothing after the matching elements
49
50 934 aaronmk
def list_subset(list_, idxs):
51
    subset = []
52
    for idx in idxs:
53
        try: subset.append(list_[idx])
54
        except IndexError: pass
55
    return subset
56
57 791 aaronmk
class CheckedIter:
58
    def __init__(self, check_func, iterable):
59
        self.check_func = check_func
60
        self.iter_ = iterable.__iter__()
61
62
    def __iter__(self): return self
63
64
    def next(self):
65
        entry = self.iter_.next()
66
        if self.check_func(entry): return entry
67
        else: raise ConstraintError(self.check_func, entry)
68
69 1008 aaronmk
#### Lists
70
71
def list_get(list_, idx, default=None):
72
    try: return list_[idx]
73
    except IndexError: return default
74
75 1012 aaronmk
def list_eq_is(list0, list1):
76
    '''Compares two lists using is'''
77
    if len(list0) != len(list1): return False
78
    for i in xrange(len(list0)):
79
        if list0[i] is not list1[i]: return False
80
    return True
81
82 791 aaronmk
#### Dicts
83
84 330 aaronmk
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
85 466 aaronmk
86 467 aaronmk
def dict_subset(dict_, keys):
87
    subset = dict()
88
    for key in keys:
89
        try: subset[key] = dict_[key]
90
        except KeyError: pass
91
    return subset