Skip to content

Instantly share code, notes, and snippets.

@earonesty
Created December 14, 2021 15:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earonesty/b88d60cb256b71443e42c4f1d949163e to your computer and use it in GitHub Desktop.
Save earonesty/b88d60cb256b71443e42c4f1d949163e to your computer and use it in GitHub Desktop.
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