Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jcrist
Created October 23, 2014 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcrist/c451f3bdd6d038521a12 to your computer and use it in GitHub Desktop.
Save jcrist/c451f3bdd6d038521a12 to your computer and use it in GitHub Desktop.
Example of a pseudo-timeout implementation for short, recursive calls
import time
def timer(timeout):
"""Creates a timer callback function. Function will return True if
the time is up, otherwise returns False."""
TIME = time.time() + timeout
def callback():
if time.time() > TIME:
return True
else:
return False
return callback
def testrecur(n, tcb=None):
"""The recursive function. Checks for timeout first. If not timed out,
computes the function result, otherwise raises a TimeoutError."""
# Boilerplate check for timeout
if not tcb or not tcb():
# This is the actual function block
if n:
time.sleep(1)
return n + testrecur(n - 1, tcb)
else:
return 0
# More boilerplate - returning error if timedout
else:
raise TimeoutError()
def test(n, timeout=None):
"""The entry point for this function. Creates a timeout callback, calls the
recursive function. If timeout, just returns the argument, otherwise return
the result."""
# Create the timeout callback
if timeout:
tcb = timer(timeout)
else:
tcb = lambda: False
# Call the recursive function. IF it times out, return the argument instead
try:
return testrecur(n, tcb=tcb)
except TimeoutError:
return n
if __name__ == '__main__':
# This will return in 5 seconds
print(test(5))
# We can force it to return in ~2 seconds with a timeout
print(test(5, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment