[issue36666] threading.Thread should have way to catch an exception thrown within
Eric Snow
report at bugs.python.org
Fri Apr 19 17:03:42 EDT 2019
Eric Snow <ericsnowcurrently at gmail.com> added the comment:
Here's a basic decorator along those lines, similar to one that I've used on occasion:
def as_thread(target):
def _target():
try:
t.result = target()
except Exception as exc:
t.failure = exc
t = threading.Thread(target=_target)
return t
Sure, it's border-line non-trivial, but I'd hardly call it "exceptionally complicated".
Variations for more flexibility:
def as_thread(target=None, **tkwds):
# A decorator to create a one-off thread from a function.
if target is None:
# Used as a decorator factory
return lambda target: as_thread(target, **tkwds)
def _target(*args, **kwargs):
try:
t.result = target(*args, **kwargs)
except Exception as exc:
t.failure = exc
t = threading.Thread(target=_target, **tkwds)
return t
def threaded(target, **tkwds):
# A decorator to produce a started thread when the "function" is called.
if target is None:
# Used as a decorator factory
return lambda target: as_thread(target, **tkwds)
@functools.wraps(target)
def wrapper(*targs, **tkwargs)
def _target(*args, *kwargs):
try:
t.result = target(*args, **kwargs)
except Exception as exc:
t.failure = exc
t = threading.Thread(target=_target, args=targs, kwargs=tkwargs, **tkwds)
t.start()
return t
return wrapper
----------
nosy: +eric.snow
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36666>
_______________________________________
More information about the Python-bugs-list
mailing list