Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Web & HTTP PythonMiddleVery commonPractical

Implement polling that waits until a condition becomes true, but never waits forever.

Answer

Use a monotonic deadline based on `time.monotonic()` rather than counting loop iterations or comparing wall-clock timestamps. Check the condition, return as soon as it succeeds, sleep for a bounded interval between attempts, and raise `TimeoutError` once the deadline is reached. A monotonic clock cannot jump backward or forward when system time changes.

Strong answer includes

  • uses time.monotonic for the deadline
  • returns immediately on success
  • raises a bounded timeout instead of looping forever

Practical example

Deadline-based polling helper
Python
editable · browser sandbox
Result
Run the code to see the result.

The absolute monotonic deadline keeps the total wait bounded even when the number of iterations varies.

Expected result: Returns the first truthy check result, otherwise raises TimeoutError after approximately the configured timeout.

#polling#timeout#retry#automation

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules