forked from JulienPalard/Pipe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipe.py
366 lines (269 loc) · 7.48 KB
/
pipe.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
#!/usr/bin/env python
"""Module enabling a sh like infix syntax (using pipes).
"""
import functools
import itertools
import socket
import sys
from contextlib import closing
from collections import deque
try:
import builtins
except ImportError:
import __builtin__ as builtins
__author__ = 'Julien Palard <[email protected]>'
__credits__ = """Jerome Schneider, for its Python skillz,
and dalexander for contributing"""
__date__ = '10 Nov 2010'
__version__ = '1.4.2'
__all__ = [
'Pipe', 'take', 'tail', 'skip', 'all', 'any', 'average', 'count',
'max', 'min', 'as_dict', 'as_set', 'permutations', 'netcat', 'netwrite',
'traverse', 'concat', 'as_list', 'as_tuple', 'stdout', 'lineout',
'tee', 'add', 'first', 'chain', 'select', 'where', 'take_while',
'skip_while', 'aggregate', 'groupby', 'sort', 'reverse',
'chain_with', 'islice', 'izip', 'passed', 'index', 'strip',
'lstrip', 'rstrip', 'run_with', 't', 'to_type', 'transpose',
'dedup', 'uniq',
]
class Pipe:
"""
Represent a Pipeable Element :
Described as :
first = Pipe(lambda iterable: next(iter(iterable)))
and used as :
print [1, 2, 3] | first
printing 1
Or represent a Pipeable Function :
It's a function returning a Pipe
Described as :
select = Pipe(lambda iterable, pred: (pred(x) for x in iterable))
and used as :
print [1, 2, 3] | select(lambda x: x * 2)
# 2, 4, 6
"""
def __init__(self, function):
self.function = function
functools.update_wrapper(self, function)
def __ror__(self, other):
return self.function(other)
def __call__(self, *args, **kwargs):
return Pipe(lambda x: self.function(x, *args, **kwargs))
@Pipe
def take(iterable, qte):
"Yield qte of elements in the given iterable."
for item in iterable:
if qte > 0:
qte -= 1
yield item
else:
return
@Pipe
def tail(iterable, qte):
"Yield qte of elements in the given iterable."
return deque(iterable, maxlen=qte)
@Pipe
def skip(iterable, qte):
"Skip qte elements in the given iterable, then yield others."
for item in iterable:
if qte == 0:
yield item
else:
qte -= 1
@Pipe
def dedup(iterable):
"""Only yield unique items. Use a set to keep track of duplicate data."""
seen = set()
for item in iterable:
if item not in seen:
seen.add(item)
yield item
@Pipe
def uniq(iterable):
"""Deduplicate consecutive duplicate values."""
iterator = iter(iterable)
try:
prev = next(iterator)
except StopIteration:
return
yield prev
for item in iterator:
if item != prev:
yield item
prev = item
@Pipe
def all(iterable, pred):
"""Returns True if ALL elements in the given iterable are true for the
given pred function"""
return builtins.all(pred(x) for x in iterable)
@Pipe
def any(iterable, pred):
"""Returns True if ANY element in the given iterable is True for the
given pred function"""
return builtins.any(pred(x) for x in iterable)
@Pipe
def average(iterable):
"""Build the average for the given iterable, starting with 0.0 as seed
Will try a division by 0 if the iterable is empty...
"""
total = 0.0
qte = 0
for element in iterable:
total += element
qte += 1
return total / qte
@Pipe
def count(iterable):
"Count the size of the given iterable, walking thrue it."
count = 0
for element in iterable:
count += 1
return count
@Pipe
def max(iterable, **kwargs):
return builtins.max(iterable, **kwargs)
@Pipe
def min(iterable, **kwargs):
return builtins.min(iterable, **kwargs)
@Pipe
def as_dict(iterable):
return dict(iterable)
@Pipe
def as_set(iterable):
return set(iterable)
@Pipe
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
for x in itertools.permutations(iterable, r):
yield x
@Pipe
def netcat(to_send, host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.connect((host, port))
for data in to_send | traverse:
s.send(data)
while 1:
data = s.recv(4096)
if not data:
break
yield data
@Pipe
def netwrite(to_send, host, port):
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.connect((host, port))
for data in to_send | traverse:
s.send(data)
@Pipe
def traverse(args):
for arg in args:
try:
if isinstance(arg, str):
yield arg
else:
for i in arg | traverse:
yield i
except TypeError:
# not iterable --- output leaf
yield arg
@Pipe
def concat(iterable, separator=", "):
return separator.join(map(str, iterable))
@Pipe
def as_list(iterable):
return list(iterable)
@Pipe
def as_tuple(iterable):
return tuple(iterable)
@Pipe
def stdout(x):
sys.stdout.write(str(x))
@Pipe
def lineout(x):
sys.stdout.write(str(x) + "\n")
@Pipe
def tee(iterable):
for item in iterable:
sys.stdout.write(str(item) + "\n")
yield item
@Pipe
def write(iterable, fname, glue='\n'):
with open(fname, 'w') as f:
for item in iterable:
f.write(str(item) + glue)
@Pipe
def add(x):
return sum(x)
@Pipe
def first(iterable):
return next(iter(iterable))
@Pipe
def chain(iterable):
return itertools.chain(*iterable)
@Pipe
def select(iterable, selector):
return (selector(x) for x in iterable)
@Pipe
def where(iterable, predicate):
return (x for x in iterable if (predicate(x)))
@Pipe
def take_while(iterable, predicate):
return itertools.takewhile(predicate, iterable)
@Pipe
def skip_while(iterable, predicate):
return itertools.dropwhile(predicate, iterable)
@Pipe
def aggregate(iterable, function, **kwargs):
if 'initializer' in kwargs:
return functools.reduce(function, iterable, kwargs['initializer'])
return functools.reduce(function, iterable)
@Pipe
def groupby(iterable, keyfunc):
return itertools.groupby(sorted(iterable, key=keyfunc), keyfunc)
@Pipe
def sort(iterable, **kwargs):
return sorted(iterable, **kwargs)
@Pipe
def reverse(iterable):
return reversed(iterable)
@Pipe
def passed(x):
pass
@Pipe
def index(iterable, value, start=0, stop=None):
return iterable.index(value, start, stop or len(iterable))
@Pipe
def strip(iterable, chars=None):
return iterable.strip(chars)
@Pipe
def rstrip(iterable, chars=None):
return iterable.rstrip(chars)
@Pipe
def lstrip(iterable, chars=None):
return iterable.lstrip(chars)
@Pipe
def run_with(iterable, func):
return (func(**iterable) if isinstance(iterable, dict) else
func(*iterable) if hasattr(iterable, '__iter__') else
func(iterable))
@Pipe
def t(iterable, y):
if hasattr(iterable, '__iter__') and not isinstance(iterable, str):
return iterable + type(iterable)([y])
return [iterable, y]
@Pipe
def to_type(x, t):
return t(x)
@Pipe
def transpose(iterable):
return list(zip(*iterable))
chain_with = Pipe(itertools.chain)
islice = Pipe(itertools.islice)
# Python 2 & 3 compatibility
if "izip" in dir(itertools):
izip = Pipe(itertools.izip)
else:
izip = Pipe(zip)
if __name__ == "__main__":
import doctest
doctest.testfile('README.md')