Project

General

Profile

1
# Useful functions and classes
2

    
3
#### Function wrappers for statements
4

    
5
def noop(*args, **kw_args): pass
6

    
7
def and_(a, b): return a and b
8

    
9
#### Object metadata
10

    
11
def type_name(value): return type(value).__name__
12

    
13
def module(value): return type(value).__module__.split('.')
14

    
15
def root_module(value): return module(value)[0]
16

    
17
#### Type checking
18

    
19
class ConstraintError(ValueError):
20
    def __init__(self, check_func, value):
21
        ValueError.__init__(self, str(value)+' must satisfy constraint '
22
            +check_func.__name__)
23

    
24
def cast(type_, val):
25
    '''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
    return val
29

    
30
def is_str(val): return isinstance(val, basestring)
31

    
32
def is_list(val): return isinstance(val, list)
33

    
34
#### 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
#### Iterables
41

    
42
def first(iter_): return iter_.next()
43

    
44
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
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
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
#### Lists
70

    
71
def list_get(list_, idx, default=None):
72
    try: return list_[idx]
73
    except IndexError: return default
74

    
75
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
#### Dicts
83

    
84
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
85

    
86
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
(13-13/16)