Skip to content

Instantly share code, notes, and snippets.

@clintval
Created February 8, 2019 18:13
Show Gist options
  • Save clintval/f5653b1265a15ba866b19ddcdea65a33 to your computer and use it in GitHub Desktop.
Save clintval/f5653b1265a15ba866b19ddcdea65a33 to your computer and use it in GitHub Desktop.
Yo hold up.
from typing import Any, Callable, Optional
class wait_callable_true(object):
"""Wait until a callable evaluates to a truthy statement, then continue.
This object can be used as a function or as a context manager.
Args:
callable: A function which should eventually return a truthy value.
call_rate: The rate at which to test the callable, optional.
Examples:
>>> iterable = [False, True, True, False, False]
>>> with wait_callable_true(iterable.pop):
... print(iterable)
[False, True]
>>> # Trivial example of waiting a quarter of a second
>>> wait_callable_true(lambda: time.sleep(0.25) or 1)
>>> print(repr('done!'))
'done!'
"""
def __init__(self, statement: Callable, call_rate: Optional[int] = None) -> None:
self.statement = statement
self.call_rate = call_rate
while not self.statement():
if self.call_rate is not None:
time.sleep(self.call_rate)
def __enter__(self) -> None:
"""Do nothing on enter."""
pass
def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
"""Do nothing on exit."""
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment