-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.py
47 lines (33 loc) · 1.01 KB
/
pipeline.py
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
import types
class Pipeline(object):
methods = {}
@classmethod
def register(cls, func):
cls.methods[func.__name__] = func
return func
def __init__(self):
super(Pipeline, self).__init__()
self.gen = []
def __getattr__(self, name):
if name not in self.methods:
raise AttributeError
def inner(self, *args, **kwargs):
self.gen = self.methods[name](self.gen, *args, **kwargs)
return self
return types.MethodType(inner, self)
def __iter__(self):
return self.gen.__iter__()
@Pipeline.register
def map(lst, fn, *args, **kwargs):
return (fn(elm, *args, **kwargs) for elm in lst)
@Pipeline.register
def filter(lst, fn, *args, **kwargs):
return (elm for elm in lst if fn(elm, *args, **kwargs))
@Pipeline.register
def take(lst, count, start=0, step=1):
for i in range(start):
next(lst)
for i in range(count):
yield next(lst)
for i in range(step-1):
next(lst)