2

I am in search of a way to threading with wrapper, yet, the result of wrapped function MUST be still available.

Via searching Stackoverflow, a not so perfect solution appreared. As the code below:

def thread_run(func):
    """
    :param func:
    :return:
    """
    def wrapper(*args, **kwargs):
        s = threading.Thread(target=func, args=args, kwargs=kwargs)
        s.daemon = True
        s.start()
        return s
    return wrapper

with this wrapper do not suffice, because:

@thread_run
def powers(number):
    return number**2


if __name__ in "__main__":
   print(powers(2))  #out put <Thread(Thread-1, stopped daemon 123145406771200)>

I want the output of snippet to be 4 print(powers(2))

what should i do?

Elias
  • 49
  • 3
  • 2
    You want the function to start a new thread, but then want the result of the thread? The wrapper would have to block to wait for that result, in which case there's little reason to start a new thread in the first place. – chepner Oct 17 '19 at 13:10
  • 2
    It is pretty clear why you are not getting the desired value (you return the ``Thread``, not the result of ``func``) but entirely unclear what your desired behaviour is. If ``print(powers(2))`` is supposed to output ``4``, *it has to wait for the thread to finish*. This defeats the purpose of using a thread in the first place. Are you looking for [futures](https://docs.python.org/3/library/concurrent.futures.html#future-objects) perhaps? – MisterMiyagi Oct 17 '19 at 13:14

0 Answers0