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
#### Iterables
32

    
33
def first(iter_): return iter_.next()
34

    
35
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
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
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
56

    
57
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
(11-11/14)