Project

General

Profile

1
# Useful functions and classes
2

    
3
#### Object metadata
4

    
5
def type_name(value): return type(value).__name__
6

    
7
def module(value): return type(value).__module__.split('.')
8

    
9
def root_module(value): return module(value)[0]
10

    
11
#### Basic types
12

    
13
class ConstraintError(ValueError):
14
    def __init__(self, check_func, value):
15
        ValueError.__init__(self, str(value)+' must satisfy constraint '
16
            +check_func.__name__)
17

    
18
def cast(type_, val):
19
    '''Passes None through'''
20
    if val != None: val = type_(val)
21
    return val
22

    
23
def is_str(val): return isinstance(val, basestring)
24

    
25
#### Iterables
26

    
27
def first(iter_): return iter_.next()
28

    
29
def skip(iter_, func):
30
    # Advance iter while func is True
31
    try:
32
        while func(iter_.curr()): iter_.next()
33
    except StopIteration: pass # nothing after the matching elements
34

    
35
class CheckedIter:
36
    def __init__(self, check_func, iterable):
37
        self.check_func = check_func
38
        self.iter_ = iterable.__iter__()
39
    
40
    def __iter__(self): return self
41
    
42
    def next(self):
43
        entry = self.iter_.next()
44
        if self.check_func(entry): return entry
45
        else: raise ConstraintError(self.check_func, entry)
46

    
47
#### Dicts
48

    
49
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
50

    
51
def dict_subset(dict_, keys):
52
    subset = dict()
53
    for key in keys:
54
        try: subset[key] = dict_[key]
55
        except KeyError: pass
56
    return subset
(11-11/14)