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 |
836
|
aaronmk
|
def cast(type_, val):
|
19 |
|
|
'''Passes None through'''
|
20 |
|
|
if val != None: val = type_(val)
|
21 |
|
|
return val
|
22 |
|
|
|
23 |
791
|
aaronmk
|
def is_str(val): return isinstance(val, basestring)
|
24 |
|
|
|
25 |
|
|
#### Iterables
|
26 |
|
|
|
27 |
135
|
aaronmk
|
def first(iter_): return iter_.next()
|
28 |
|
|
|
29 |
133
|
aaronmk
|
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 |
791
|
aaronmk
|
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 |
330
|
aaronmk
|
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
|
50 |
466
|
aaronmk
|
|
51 |
467
|
aaronmk
|
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
|