Created
December 18, 2019 02:54
-
-
Save alkasm/ef17606103eb0854346ee1d9fffee9c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from concurrent.futures import ThreadPoolExecutor, TimeoutError | |
class TimeoutIterable: | |
"""Iterable that exhausts if it takes longer than `timeout` seconds to obtain the next value.""" | |
def __init__(self, iterable, timeout=None): | |
self._it = iter(iterable) | |
self.timeout = timeout | |
def __iter__(self): | |
with ThreadPoolExecutor(max_workers=1) as executor: | |
while True: | |
try: | |
future = executor.submit(next, self._it) | |
val = future.result(self.timeout) | |
except (TimeoutError, StopIteration): | |
return | |
yield val | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment