1

I've been using Python for years now, and recently I've discovered asynchronies programming. However, I'm having a rough time trying to implement my ideas...

Let's say I have a regular (synchronized) function g() that returns a value that it computes. Inside this function, I want to call another function, that is asynchronies and runs in a loop - we will call this function f(). The function f() is called inside g(), but the returned value of g() is computed before f() is even called. However, obviously, I want g() to return the value it computed and keep running f() "in the background".

import asyncio


def g(a, b):
    y = a + b
    asyncio.run(f())    # This is blocking!
    return y


async def f():
    for _ in range(3):
        await asyncio.sleep(1)
        print("I'm still alive!")

print(g(3, 5))
# code async code continues here...


# Output:
# I'm still alive!
# I'm still alive!
# I'm still alive!
# 8

# Expected\Wanted:
# 8
# I'm still alive!
# I'm still alive!
# I'm still alive!

Is something like this is even possible? Or am I missing something? Thanks in advance!

RealA10N
  • 120
  • 1
  • 5
  • 19

1 Answers1

1

There are a few misunderstandings I believe. So first of all, you cannot have something really simultaneous without using thread or process. async is syntax sugar for the callback-based event-driven architecture.

Shortly, they are still in the same thread, and as you know, one thread can do only one thing at one time. If you want to have a kind of background task running and printing "I'm still alive", then async is not what you are looking for.

Also, Aren't you curious about where is the event loop? The loop is created and managed by asyncio.run, it roughly equals to:

loop = asyncio.get_event_loop()
loop.run_until_complete(f())

So you see, you need to run/trigger the loop, and it is blocking.


Basically, the asynchronies programming doesn't work as you thought(I guess). There is no magic inside, it is just a normal blocking event loop. We add multiple tasks into it, and all the tasks are running one by one. Some tasks have callback functions, which adds another task into the loop. That's it.

Sraw
  • 18,892
  • 11
  • 54
  • 87