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 791 aaronmk
class CheckedIter:
42
    def __init__(self, check_func, iterable):
43
        self.check_func = check_func
44
        self.iter_ = iterable.__iter__()
45
46
    def __iter__(self): return self
47
48
    def next(self):
49
        entry = self.iter_.next()
50
        if self.check_func(entry): return entry
51
        else: raise ConstraintError(self.check_func, entry)
52
53
#### Dicts
54
55 330 aaronmk
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
56 466 aaronmk
57 467 aaronmk
def dict_subset(dict_, keys):
58
    subset = dict()
59
    for key in keys:
60
        try: subset[key] = dict_[key]
61
        except KeyError: pass
62
    return subset