-
Notifications
You must be signed in to change notification settings - Fork 560
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
57 additions
and
3 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import asyncio | ||
import signal | ||
from contextlib import contextmanager | ||
from functools import wraps | ||
|
||
|
||
def coroutine_timeout(seconds): | ||
def decorator(func): | ||
@wraps(func) | ||
async def wrapper(*args, **kwargs): | ||
try: | ||
if asyncio.iscoroutinefunction(func): | ||
return await asyncio.wait_for( | ||
func(*args, **kwargs), timeout=seconds | ||
) | ||
else: | ||
raise TypeError( | ||
f"Function {func.__name__} is not a coroutine function" | ||
) | ||
except asyncio.TimeoutError: | ||
raise_timeout_error(seconds) | ||
|
||
return wrapper | ||
|
||
return decorator | ||
|
||
|
||
@contextmanager | ||
def timeout(seconds: int): | ||
signal.signal( | ||
signal.SIGALRM, lambda signum, frame: raise_timeout_error(seconds) | ||
) | ||
signal.alarm(seconds) | ||
|
||
try: | ||
yield | ||
finally: | ||
signal.signal(signal.SIGALRM, signal.SIG_IGN) | ||
|
||
|
||
def raise_timeout_error(seconds): | ||
raise TimeoutError(f"Timeout occurred after {seconds} seconds") from None |
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
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