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
#### Basic types
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'''
26
    if val != None: val = type_(val)
27
    return val
28

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

    
31
#### Strings
32

    
33
def to_percent(val, sig_figs=2):
34
    if val >= 1: sig_figs += 1
35
    return (('%#.'+str(sig_figs)+'g') % (val*100))+'%'
36

    
37
#### Iterables
38

    
39
def first(iter_): return iter_.next()
40

    
41
def skip(iter_, func):
42
    # Advance iter while func is True
43
    try:
44
        while func(iter_.curr()): iter_.next()
45
    except StopIteration: pass # nothing after the matching elements
46

    
47
def list_subset(list_, idxs):
48
    subset = []
49
    for idx in idxs:
50
        try: subset.append(list_[idx])
51
        except IndexError: pass
52
    return subset
53

    
54
class CheckedIter:
55
    def __init__(self, check_func, iterable):
56
        self.check_func = check_func
57
        self.iter_ = iterable.__iter__()
58
    
59
    def __iter__(self): return self
60
    
61
    def next(self):
62
        entry = self.iter_.next()
63
        if self.check_func(entry): return entry
64
        else: raise ConstraintError(self.check_func, entry)
65

    
66
#### Dicts
67

    
68
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
69

    
70
def dict_subset(dict_, keys):
71
    subset = dict()
72
    for key in keys:
73
        try: subset[key] = dict_[key]
74
        except KeyError: pass
75
    return subset
(11-11/14)