Created
November 26, 2025 12:19
-
-
Save LukasForst/9900aa910e4eaad40a0c66a45b623077 to your computer and use it in GitHub Desktop.
Async works differently in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| async def child(): | |
| print("child start") | |
| await asyncio.sleep(2) | |
| print("child end") | |
| # correct way how to do async in Python | |
| async def parent_correct_async(): | |
| print("parent before") | |
| # craetes async task that is executed | |
| task = asyncio.create_task(child()) | |
| # now we yield | |
| await asyncio.sleep(1) | |
| print("parent after creating task") | |
| # and now we wait for task to finish | |
| await task | |
| print("parent after await") | |
| # ! incorrrect way to do async, there's no concurency involved | |
| async def parent_wrong_async(): | |
| print("parent before") | |
| # this creates coroutine BUT DOES NOT EXECUTE IT | |
| coroutine = child() | |
| # now we yield | |
| await asyncio.sleep(1) | |
| print("parent after creating task") | |
| # THIS STARTS EXECUTION | |
| await coroutine | |
| print("parent after await") | |
| if __name__ == '__main__': | |
| print("running correct async\n----------") | |
| asyncio.run(parent_correct_async()) | |
| print("\nrunning WRONG async\n----------") | |
| asyncio.run(parent_wrong_async()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment