-
-
Save jcrist/c451f3bdd6d038521a12 to your computer and use it in GitHub Desktop.
Example of a pseudo-timeout implementation for short, recursive calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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