Skip to content

Commit 7c5a344

Browse files
author
czheo
committed
add lazy_pipe
1 parent d2fc434 commit 7c5a344

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

syntax_sugar/pipe.py

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from functools import partial
2-
from .composable import compose
2+
from .composable import compose, composable
33
from multiprocess.pool import ThreadPool, Pool
44

55
__all__ = [
@@ -15,6 +15,9 @@
1515
'thread_syntax',
1616
'p',
1717
't',
18+
'until',
19+
'when',
20+
'lazy_pipe',
1821
]
1922

2023
def puts(data):
@@ -129,42 +132,51 @@ def __rshift__(self, rhs):
129132
# lazy_pipe
130133
#####
131134

135+
def neg(x):
136+
return not x
137+
132138
class until:
133139
def __init__(self, cond):
134140
self.cond = cond
135141

142+
class when:
143+
def __init__(self, cond):
144+
self.cond = cond
145+
136146
class lazy_pipe:
137147
def __init__(self, source):
138148
self.source = source
139149
self.func = composable(lambda x: x)
140150

141-
def __or__(self, left):
142-
if isinstance(left, dump):
151+
def __or__(self, rhs):
152+
if isinstance(rhs, dump):
143153
# dump termination
144154
return self.dump()
145-
elif isinstance(left, until):
146-
return self.until(left.cond)
155+
elif isinstance(rhs, when):
156+
return self.when(rhs.cond)
157+
elif isinstance(rhs, until):
158+
return self.when(compose(neg, rhs.cond))
147159
else:
148160
# read actions
149-
self.func = composable(left) * self.func
161+
self.func = composable(rhs) * self.func
150162
return self
151163

152164
def dump(self):
153165
return self.func(self.source)
154166

155-
def until(self, cond):
167+
def when(self, cond):
156168
if hasattr(self.source, '__call__'):
157169
data = self.source()
158-
while not cond(data):
170+
while cond(data):
159171
self.func(data)
160172
data = self.source()
161173
return self
162174
elif hasattr(self.source, '__iter__'):
163175
for data in self.source:
164176
if cond(data):
165-
break
166-
else:
167177
self.func(data)
178+
else:
179+
break
168180
return self
169181
else:
170182
raise TypeError('pipeline source need be callable or iterable with until condition')

0 commit comments

Comments
 (0)