Message340557
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 |
|
Date |
User |
Action |
Args |
2019-04-19 21:03:42 | eric.snow | set | recipients:
+ eric.snow, tim.peters, pitrou, giampaolo.rodola, pablogsal, Joel Croteau |
2019-04-19 21:03:42 | eric.snow | set | messageid: <1555707822.68.0.681092744917.issue36666@roundup.psfhosted.org> |
2019-04-19 21:03:42 | eric.snow | link | issue36666 messages |
2019-04-19 21:03:42 | eric.snow | create | |
|