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 is_str(val): return isinstance(val, basestring)
19

    
20
#### Iterables
21

    
22
def first(iter_): return iter_.next()
23

    
24
def skip(iter_, func):
25
    # Advance iter while func is True
26
    try:
27
        while func(iter_.curr()): iter_.next()
28
    except StopIteration: pass # nothing after the matching elements
29

    
30
class CheckedIter:
31
    def __init__(self, check_func, iterable):
32
        self.check_func = check_func
33
        self.iter_ = iterable.__iter__()
34
    
35
    def __iter__(self): return self
36
    
37
    def next(self):
38
        entry = self.iter_.next()
39
        if self.check_func(entry): return entry
40
        else: raise ConstraintError(self.check_func, entry)
41

    
42
#### Dicts
43

    
44
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
45

    
46
def dict_subset(dict_, keys):
47
    subset = dict()
48
    for key in keys:
49
        try: subset[key] = dict_[key]
50
        except KeyError: pass
51
    return subset
(11-11/14)