Project

General

Profile

1
# Useful functions and classes
2

    
3
import collections
4

    
5
#### Function wrappers for statements
6

    
7
def noop(*args, **kw_args): pass
8

    
9
def and_(a, b): return a and b
10

    
11
#### Object metadata
12

    
13
def type_name(value): return type(value).__name__
14

    
15
def module(value): return type(value).__module__.split('.')
16

    
17
def root_module(value): return module(value)[0]
18

    
19
#### Type checking
20

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

    
26
def cast(type_, val):
27
    '''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
    return val
31

    
32
def is_str(val): return isinstance(val, basestring)
33

    
34
def is_list(val): return isinstance(val, list)
35

    
36
#### Basic types
37

    
38
def none_if(val, none_val):
39
    if cast(type(none_val), val) == none_val: return None
40
    else: return val
41

    
42
#### Iterables
43

    
44
def first(iter_): return iter_.next()
45

    
46
def skip(iter_, func):
47
    # Advance iter while func is True
48
    try:
49
        while func(iter_.curr()): iter_.next()
50
    except StopIteration: pass # nothing after the matching elements
51

    
52
def list_subset(list_, idxs):
53
    subset = []
54
    for idx in idxs:
55
        try: subset.append(list_[idx])
56
        except IndexError: pass
57
    return subset
58

    
59
class CheckedIter:
60
    def __init__(self, check_func, iterable):
61
        self.check_func = check_func
62
        self.iter_ = iterable.__iter__()
63
    
64
    def __iter__(self): return self
65
    
66
    def next(self):
67
        entry = self.iter_.next()
68
        if self.check_func(entry): return entry
69
        else: raise ConstraintError(self.check_func, entry)
70

    
71
#### Lists
72

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

    
77
def list_eq_is(list0, list1):
78
    '''Compares two lists using is'''
79
    if len(list0) != len(list1): return False
80
    for i in xrange(len(list0)):
81
        if list0[i] is not list1[i]: return False
82
    return True
83

    
84
#### Dicts
85

    
86
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
87

    
88
def dict_subset(dict_, keys):
89
    subset = dict()
90
    for key in keys:
91
        try: subset[key] = dict_[key]
92
        except KeyError: pass
93
    return subset
94

    
95
class DefaultDict(collections.defaultdict):
96
    def __init__(self, dict_, default=None):
97
        collections.defaultdict.__init__(self, lambda: default, dict_)
98

    
99
def dict_subset_right_join(dict_, keys):
100
    '''Gets a subset of a dict, using None for subset keys that don't exist'''
101
    return dict_subset(DefaultDict(dict_), keys)
(13-13/16)