Get the Return value from a Thread in Python

If you are familiar with the concept of Threads in Python, then there is a certain problem you may have faced while using them. That is, a normal Python Thread cannot have a Return Value to send back to the Main Thread from which it was created.

Now for most cases this isn’t really a problem. But sometimes this becomes necessary, or any alternative solution will be too complex. In this tutorial we will give you any easy way of solving this issue. (In fact you don’t have to do anything extra at all!)


Getting a Return Value from a Python Thread

Now, there is no built in functionality to get a return value from a Thread. No fancy feature, parameter or method will make this happen.

Luckily, nothing is stopping us from adding that functionality into the Thread Class ourselves. What we are going to do, is make a “Sub-Class” from the main Thread Class (by inheriting it) and simple make a small change here and there.

There are three changes in total that we need to make.

  1. First we add a new attribute to our class which will store the return value. (This is done in the init function, called self._return)
  2. Secondly, we make a change to the default run() method (which is called internally by Thread) to store the return value from our target function into our new attribute. self._target refers to the function we passed into our Thread when we created it.
  3. Finally, we over-ride the default join() method. We keep the original join() functionality by called Thread.join(), and then we add an extra line which returns the stored return value.

Here is the code for this Custom Thread Class.

from threading import Thread

class CustomThread(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs)
        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)
            
    def join(self, *args):
        Thread.join(self, *args)
        return self._return

Example

Now lets take a look at this new Thread Class in action. You don’t have to do anything extra after defining this Class. Just use the threads objects like you normally would. Only difference is in the class name.

In the below code we have a add() function, which sums two numbers. We will have this function execute on our new Thread, and then return the value when thread.join() is called.

from threading import Thread

class CustomThread(Thread):
    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs={}, Verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs)
        self._return = None

    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)
            
    def join(self, *args):
        Thread.join(self, *args)
        return self._return

def add(n1, n2):
    return n1 + n2

thread = CustomThread(target=add, args=(5, 3,))
thread.start()
print(thread.join()
8

This marks the end of the Get the Return value from a Thread in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments