Skip to content

Instantly share code, notes, and snippets.

@iwiwi
Created February 20, 2018 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwiwi/dc74bd4e34908a96c28b6f7e05b6eabc to your computer and use it in GitHub Desktop.
Save iwiwi/dc74bd4e34908a96c28b6f7e05b6eabc to your computer and use it in GitHub Desktop.
class RangeWithTimeout(object):
def __init__(self, n=None, timeout_seconds=None):
self.n = n
self.timeout_seconds = timeout_seconds
self.i = 0
def __iter__(self):
self.start_datetime = datetime.datetime.now()
return self
def __next__(self):
i = self.i
self.i += 1
if self.n is not None and i >= self.n:
raise StopIteration
if self.timeout_seconds is not None:
elapsed_timedelta = datetime.datetime.now() - self.start_datetime
elapsed_seconds = elapsed_timedelta.total_seconds()
if elapsed_seconds >= self.timeout_seconds:
raise StopIteration
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment