You can use a little known ctyps
hack to raise a TimeoutError
targeting a specific thread. I made a non_blocking
timeout script using this method and just released it on GitHub: https://github.com/levimluke/PyTimeoutAfter
It's SUPER simple to implement, but technically complex.
def raise_caller(self):
ret = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self._caller_thread._ident), ctypes.py_object(self._exception))
if ret == 0:
raise ValueError("Invalid thread ID")
elif ret > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(self._caller_thread._ident, NULL)
raise SystemError("PyThreadState_SetAsyncExc failed")
https://github.com/levimluke/PyTimeoutAfter/blob/main/timeout_after.py#L47
I use a class object and save the calling thread to, that way I can raise an exception in the parent class from within the timed child thread.