Skip to content

Instantly share code, notes, and snippets.

@Tbruno25
Created July 22, 2022 16:01
Show Gist options
  • Save Tbruno25/cadd6a47c0c09ab07a2faf83a4337a30 to your computer and use it in GitHub Desktop.
Save Tbruno25/cadd6a47c0c09ab07a2faf83a4337a30 to your computer and use it in GitHub Desktop.
Simple python3 timeout
import time
from contextlib import contextmanager
from typing import Iterator
@contextmanager
def timeout(seconds: float = 5) -> Iterator:
"""
A simple context manager to enable timeouts.
Args:
seconds (float): Length of timeout in seconds. Defaults to 5
Yields:
Iterator[bool]: True if timeout exceeded
Example:
with timeout(60) as t:
while True:
if t():
# handle
"""
stop = time.time() + seconds
def timed_out():
return time.time() > stop
yield timed_out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment