Last active
December 3, 2015 15:52
-
-
Save akayj/5c4f81f9d8742a98cf6f to your computer and use it in GitHub Desktop.
Useful decorator - Timeout
This file contains hidden or 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 signal | |
import functools | |
class TimeoutError(Exception): pass | |
def timeout(seconds, error_message='Function called timed out!'): | |
def _handle_timeout(signum, frame): | |
raise TimeoutError(error_message) | |
def decorator(func): | |
def wrapper(*a, **kw): | |
signal.signal(signal.SIGALRM, _handle_timeout) | |
signal.alarm(seconds) | |
try: | |
result = func(*a, **kw) | |
return result | |
finally: | |
signal.alarm(0) | |
return functools.update_wrapper(wrapper, func) | |
return decorator | |
# Example | |
@timeout(.5) | |
def multiply(a, b): | |
import time | |
time.sleep(1) | |
return a * b | |
multiply(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment