1
|
# Useful functions and classes
|
2
|
|
3
|
import locale
|
4
|
|
5
|
locale.setlocale(locale.LC_ALL, '') # needed to initialize locale
|
6
|
|
7
|
#### Function wrappers for statements
|
8
|
|
9
|
def noop(*args, **kw_args): pass
|
10
|
|
11
|
def and_(a, b): return a and b
|
12
|
|
13
|
#### Object metadata
|
14
|
|
15
|
def type_name(value): return type(value).__name__
|
16
|
|
17
|
def module(value): return type(value).__module__.split('.')
|
18
|
|
19
|
def root_module(value): return module(value)[0]
|
20
|
|
21
|
#### Basic types
|
22
|
|
23
|
class ConstraintError(ValueError):
|
24
|
def __init__(self, check_func, value):
|
25
|
ValueError.__init__(self, str(value)+' must satisfy constraint '
|
26
|
+check_func.__name__)
|
27
|
|
28
|
def cast(type_, val):
|
29
|
'''Passes None through'''
|
30
|
if val != None: val = type_(val)
|
31
|
return val
|
32
|
|
33
|
def is_str(val): return isinstance(val, basestring)
|
34
|
|
35
|
#### Strings
|
36
|
|
37
|
def format_str(format, val):
|
38
|
return locale.format_string(format, val, grouping=True)
|
39
|
|
40
|
def to_percent(val, sig_figs=2):
|
41
|
if val >= 1: sig_figs += 1
|
42
|
return format_str('%#.'+str(sig_figs)+'g', val*100)+'%'
|
43
|
|
44
|
#### Iterables
|
45
|
|
46
|
def first(iter_): return iter_.next()
|
47
|
|
48
|
def skip(iter_, func):
|
49
|
# Advance iter while func is True
|
50
|
try:
|
51
|
while func(iter_.curr()): iter_.next()
|
52
|
except StopIteration: pass # nothing after the matching elements
|
53
|
|
54
|
def list_subset(list_, idxs):
|
55
|
subset = []
|
56
|
for idx in idxs:
|
57
|
try: subset.append(list_[idx])
|
58
|
except IndexError: pass
|
59
|
return subset
|
60
|
|
61
|
class CheckedIter:
|
62
|
def __init__(self, check_func, iterable):
|
63
|
self.check_func = check_func
|
64
|
self.iter_ = iterable.__iter__()
|
65
|
|
66
|
def __iter__(self): return self
|
67
|
|
68
|
def next(self):
|
69
|
entry = self.iter_.next()
|
70
|
if self.check_func(entry): return entry
|
71
|
else: raise ConstraintError(self.check_func, entry)
|
72
|
|
73
|
#### Dicts
|
74
|
|
75
|
def rename_key(dict_, orig, new): dict_[new] = dict_.pop(orig)
|
76
|
|
77
|
def dict_subset(dict_, keys):
|
78
|
subset = dict()
|
79
|
for key in keys:
|
80
|
try: subset[key] = dict_[key]
|
81
|
except KeyError: pass
|
82
|
return subset
|