1 |
11
|
aaronmk
|
# Useful functions and classes
|
2 |
|
|
|
3 |
791
|
aaronmk
|
#### Object metadata
|
4 |
|
|
|
5 |
341
|
aaronmk
|
def type_name(value): return type(value).__name__
|
6 |
|
|
|
7 |
135
|
aaronmk
|
def module(value): return type(value).__module__.split('.')
|
8 |
|
|
|
9 |
|
|
def root_module(value): return module(value)[0]
|
10 |
|
|
|
11 |
791
|
aaronmk
|
#### Basic types
|
12 |
|
|
|
13 |
|
|
class ConstraintError(ValueError):
|
14 |
|
|
def __init__(self, check_func, value):
|
15 |
795
|
aaronmk
|
ValueError.__init__(self, str(value)+' must satisfy constraint '
|
16 |
|
|
+check_func.__name__)
|
17 |
791
|
aaronmk
|
|
18 |
|
|
def is_str(val): return isinstance(val, basestring)
|
19 |
|
|
|
20 |
|
|
#### Iterables
|
21 |
|
|
|
22 |
135
|
aaronmk
|
def first(iter_): return iter_.next()
|
23 |
|
|
|
24 |
133
|
aaronmk
|
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 |
791
|
aaronmk
|
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 |
330
|
aaronmk
|
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
|
45 |
466
|
aaronmk
|
|
46 |
467
|
aaronmk
|
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
|