Skip to content

Instantly share code, notes, and snippets.

@cchurch
Created November 16, 2016 22:05
Show Gist options
  • Save cchurch/c54a2d01cd7cbe4abc0872cb2abf644b to your computer and use it in GitHub Desktop.
Save cchurch/c54a2d01cd7cbe4abc0872cb2abf644b to your computer and use it in GitHub Desktop.
Timeout class - initialize with a duration, evaluates as boolean True until timeout has expired.
# Python
import time
__all__ = ['Timeout']
class Timeout(object):
def __init__(self, duration=None):
# If initializing from another instance, create a new timeout from the
# remaining time on the other.
if isinstance(duration, Timeout):
duration = duration.remaining
self.reset(duration)
def __repr__(self):
if self._duration is None:
return 'Timeout(None)'
else:
return 'Timeout(%f)' % self._duration
def __hash__(self):
return self._duration
def __nonzero__(self):
return self.block
def _get_current_time(self):
return time.time()
def reset(self, duration=False):
if duration is not False:
self._duration = float(max(0, duration)) if duration is not None else None
self._begin = self._get_current_time()
def expire(self):
self._begin = self._get_current_time() - max(0, self._duration or 0.0)
@property
def duration(self):
return self._duration
@property
def elapsed(self):
return float(max(0, self._get_current_time() - self._begin))
@property
def remaining(self):
if self._duration is None:
return None
else:
return float(max(0, self._duration + self._begin - self._get_current_time()))
@property
def block(self):
remaining = self.remaining
return bool(remaining or remaining is None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment