Created
December 14, 2021 15:43
-
-
Save earonesty/b88d60cb256b71443e42c4f1d949163e to your computer and use it in GitHub Desktop.
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 threading | |
from typing import Any | |
class PropagatingThread(threading.Thread): | |
"""A Threading Class that raises errors it caught, and returns the return value of the target on join.""" | |
def __init__(self, *args, **kwargs): | |
self._target = None | |
self._args = () | |
self._kwargs = {} | |
super().__init__(*args, **kwargs) | |
self.exception = None | |
self.return_value = None | |
assert self._target | |
def run(self): | |
"""Don't override this if you want the behavior of this class, use target instead.""" | |
try: | |
if self._target: | |
self.return_value = self._target(*self._args, **self._kwargs) | |
except Exception as e: | |
self.exception = e | |
finally: | |
# see super().run() for why this is necessary | |
del self._target, self._args, self._kwargs | |
def join(self, timeout=None) -> Any: | |
super().join(timeout) | |
if self.exception: | |
raise self.exception | |
return self.return_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment