-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathfunctools.py
More file actions
69 lines (60 loc) · 1.52 KB
/
functools.py
File metadata and controls
69 lines (60 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
##
# python.functools
##
import sys
from .decorlib import method
def rsetattr(attr, val, ob):
"""
setattr() and return `ob`. Different order used to allow easier partial
usage.
"""
setattr(ob, attr, val)
return ob
try:
from ..port.optimized import rsetattr
except ImportError:
pass
class Composition(tuple):
def __call__(self, r):
for x in self:
r = x(r)
return r
try:
from ..port.optimized import compose
__call__ = method(compose)
del compose
except ImportError:
pass
try:
# C implementation of the tuple processors.
from ..port.optimized import process_tuple, process_chunk
except ImportError:
def process_tuple(procs, tup, exception_handler, len = len, tuple = tuple, cause = None):
"""
Call each item in `procs` with the corresponding
item in `tup` returning the result as `type`.
If an item in `tup` is `None`, don't process it.
If a give transformation failes, call the given exception_handler.
"""
i = len(procs)
if len(tup) != i:
raise TypeError(
"inconsistent items, %d processors and %d items in row" %(
i, len(tup)
)
)
r = [None] * i
try:
for i in range(i):
ob = tup[i]
if ob is None:
continue
r[i] = procs[i](ob)
except Exception:
cause = sys.exc_info()[1]
if cause is not None:
exception_handler(cause, procs, tup, i)
raise RuntimeError("process_tuple exception handler failed to raise")
return tuple(r)
def process_chunk(procs, tupc, fail, process_tuple = process_tuple):
return [process_tuple(procs, x, fail) for x in tupc]