-
Notifications
You must be signed in to change notification settings - Fork 81
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #508 from flairNLP/add-timeout-to-publisher-coverage
Add timeout to publisher_coverage.py
- Loading branch information
Showing
2 changed files
with
70 additions
and
24 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,44 @@ | ||
import _thread as thread | ||
import threading | ||
from functools import wraps | ||
from typing import Callable, Literal, Optional, TypeVar, overload | ||
|
||
from typing_extensions import ParamSpec | ||
|
||
P = ParamSpec("P") | ||
T = TypeVar("T") | ||
|
||
|
||
def _interrupt_handler() -> None: | ||
thread.interrupt_main() | ||
|
||
|
||
@overload | ||
def timeout(func: Callable[P, T], time: float, silent: Literal[False] = ...) -> Callable[P, T]: | ||
... | ||
|
||
|
||
@overload | ||
def timeout(func: Callable[P, T], time: float, silent: Literal[True]) -> Callable[P, Optional[T]]: | ||
... | ||
|
||
|
||
def timeout(func: Callable[P, T], time: float, silent: bool = False) -> Callable[P, Optional[T]]: | ||
@wraps(func) | ||
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Optional[T]: | ||
# register interrupt handler | ||
timer = threading.Timer(time, _interrupt_handler) | ||
|
||
try: | ||
timer.start() | ||
result = func(*args, **kwargs) | ||
except KeyboardInterrupt as err: | ||
if silent: | ||
return None | ||
else: | ||
raise TimeoutError from err | ||
finally: | ||
timer.cancel() | ||
return result | ||
|
||
return wrapper |