Skip to content

Commit 23677eb

Browse files
committed
-
1 parent 2e57d64 commit 23677eb

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright 2009-2015 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
import time
5+
import concurrent.futures
6+
7+
from python_toolbox import sequence_tools
8+
9+
10+
class CuteExecutorMixin:
11+
def filter(self, filter_function, iterable, timeout=None,
12+
as_completed=False):
13+
'''Get a parallelized version of filter(filter_function, iterable).'''
14+
15+
sequence = sequence_tools.ensure_iterable_is_sequence(iterable)
16+
return (
17+
item for (item, keep) in zip(
18+
sequence,
19+
self.map(filter_function, sequence, timeout=timeout,
20+
as_completed=as_completed)
21+
) if keep
22+
)
23+
24+
def map(self, function, *iterables, timeout=None, as_completed=False):
25+
'''Get a parallelized version of map(function, iterable).'''
26+
27+
if timeout is not None:
28+
end_time = timeout + time.time()
29+
30+
futures = [self.submit(function, *args) for args in zip(*iterables)]
31+
futures_iterator = concurrent.futures.as_completed(futures) if \
32+
as_completed else futures
33+
34+
# Yield must be hidden in closure so that the futures are submitted
35+
# before the first iterator value is required.
36+
def result_iterator():
37+
try:
38+
for future in futures:
39+
if timeout is None:
40+
yield future.result()
41+
else:
42+
yield future.result(end_time - time.time())
43+
finally:
44+
for future in futures:
45+
future.cancel()
46+
return result_iterator()
47+
48+
49+
class CuteThreadPoolExecutor(CuteExecutorMixin,
50+
concurrent.futures.ThreadPoolExecutor):
51+
pass
52+
53+
class CuteProcessPoolExecutor(CuteExecutorMixin,
54+
concurrent.futures.ProcessPoolExecutor):
55+
pass

source_py3/test_python_toolbox/test_future_tools/__init__.py

Whitespace-only changes.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Copyright 2009-2015 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
import concurrent.futures
5+
import time
6+
7+
from python_toolbox import future_tools
8+
9+
10+
def test():
11+
12+
def sleep_and_return(seconds):
13+
time.sleep(seconds)
14+
return seconds
15+
16+
17+
with future_tools.CuteThreadPoolExecutor(5) as executor:
18+
assert isinstance(executor, future_tools.CuteThreadPoolExecutor)
19+
assert tuple(executor.filter(lambda x: (x % 2 == 0), range(10))) == \
20+
tuple(range(0, 10, 2))
21+
assert sorted(executor.filter(lambda x: (x % 2 == 0), range(10),
22+
timeout=10**5, as_completed=True)) == \
23+
list(range(0, 10, 2))
24+
assert tuple(executor.filter(
25+
lambda x: (sleep_and_return(x) % 2 == 0), range(9, -1, -1),
26+
as_completed=True)) == (range(0, 10, 2))
27+
28+
29+
30+

0 commit comments

Comments
 (0)