4 ms·
Not a core dev. The clean way to return a value is to pass it to a Queue (https://docs.python.org/fr/3/library/queue.html https://docs.python.org/fr/3/library/
by BiteCode_dev 7y ago
Not a core dev.
The clean way to return a value is to pass it to a Queue (https://docs.python.org/fr/3/library/queue.html https://docs.python.org/fr/3/library/queue.html), and this is what the executor does, but for your use case, it's overkill.
For very simple use cases, you can inherit from Thread and force join() to return the value:
class SimpleReturningThread(Thread):
result = None
def run(self):
try:
if self._target:
self.result = self._target(*self._args, **self._kwargs)
finally:
del self._target, self._args, self._kwargs
def join(self, *args, **kwargs):
super().join(*args, **kwargs)
return self.result
Personally, I'd stick to using a pool with only one worker in it. It's not worth the trouble of doing all this work. Wrap it in a few functions if you do the same thing repeatedly and call it a day, it's unlikely going to be what most your code is about anyway.