import time


def _poll_for_condition(
    condition, max_seconds=10, sleep_interval=0.1, desc='[unnamed condition]'):
  """Poll until a condition becomes true.

  Arguments:
    condition: callable taking no args and returning bool.
    max_seconds: maximum number of seconds to wait.
                 Might bail up to sleep_interval seconds early.
    sleep_interval: number of seconds to sleep between polls.
    desc: description put in TimeoutError.

  Returns:
    The true value that caused the poll loop to terminate.

  Raises:
    TimeoutError if condition doesn't become true before max_seconds is reached.
  """
  start_time = time.time()
  while time.time() + sleep_interval - start_time <= max_seconds:
    value = condition()
    if value:
      return value
    time.sleep(sleep_interval)

  raise TimeoutError('Timed out waiting for condition: %s' % desc)