async await - AndrewMZ6/python_cheat_sheet GitHub Wiki
To do: describe what's going on step by step
import asyncio
async def f():
print('Hey, this is function f() is executed')
await asyncio.sleep(1)
print('Hey, this is function f() is executed')
async def g():
for i in range(5):
print(f'counting {i}')
await asyncio.sleep(.3)
async def main():
await asyncio.gather(f(), g())
if __name__ == '__main__':
asyncio.run(main())
output
Hey, this is function f() is executed
counting 0
counting 1
counting 2
counting 3
Hey, this is function f() is executed
counting 4
If we change the code just a bit. Comment out the line await asyncio.sleep(.3)
in function
g
and put time.sleep(1)
instead.
import asyncio
import time
async def f():
print('Hey, this is function f() is executed')
await asyncio.sleep(1)
print('Hey, this is function f() is executed')
async def g():
for i in range(5):
print(f'counting {i}')
time.sleep(1)
# await asyncio.sleep(.3)
async def main():
await asyncio.gather(f(), g())
if __name__ == '__main__':
asyncio.run(main())
output:
Hey, this is function f() is executed
counting 0
counting 1
counting 2
counting 3
counting 4
Hey, this is function f() is executed
As we can see here function f
ceeded control to event loop when the line await asyncio.sleep(1)
was reached.
Since main
coroutine contains g
function the flow of execution is now at g
function. But as we've changed
it's sleeping
from non-blocking to blocking the function g
does not ceeds control on the execution flow and
only giong to return control to the main
coroutine when it's actualy finished. This is why the second print statement
of the f
function only appears after the g
function is done.