Skip to content

Instantly share code, notes, and snippets.

@alkasm
Created December 18, 2019 02:54
Show Gist options
  • Save alkasm/ef17606103eb0854346ee1d9fffee9c6 to your computer and use it in GitHub Desktop.
Save alkasm/ef17606103eb0854346ee1d9fffee9c6 to your computer and use it in GitHub Desktop.
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