Project

General

Profile

« Previous | Next » 

Revision 791

util.py: Added is_str() and CheckedIter

View differences:

lib/util.py
1 1
# Useful functions and classes
2 2

  
3
#### Object metadata
4

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

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

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

  
11
#### Basic types
12

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

  
18
def is_str(val): return isinstance(val, basestring)
19

  
20
#### Iterables
21

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

  
11 24
def skip(iter_, func):
......
14 27
        while func(iter_.curr()): iter_.next()
15 28
    except StopIteration: pass # nothing after the matching elements
16 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

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

  
19 46
def dict_subset(dict_, keys):

Also available in: Unified diff