sambeth
sambeth

Reputation: 1600

How to let nested function run async and not block the parent function

def A(event):
   B(event)
   return "something"

def B(event)
   return event

Let's say I have a function like the one above, how do make function A return its output and not wait for function B. The output of A does not depend on function B but function B depends on the input of function A.

Upvotes: 1

Views: 1864

Answers (1)

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39576

In your example most easy way to do it is to run B in a thread. For example:

import time
from concurrent.futures import ThreadPoolExecutor


executor = ThreadPoolExecutor(max_workers=1)


def A():
    executor.submit(B)
    print("Hi from A")

def B():
    time.sleep(1)
    print("Hi from B")


if __name__ == '__main__':
    A()

If you want to do it using asyncio, you should wrap A and B to be coroutines and use asyncio.Task. Note however that unless B is I/O related it wouldn't be possible to make it coroutine without using thread. Here's more detailed explanation.

Upvotes: 1

Related Questions