Skip to content

Instantly share code, notes, and snippets.

@harshithjv
Last active May 3, 2023 09:36
Show Gist options
  • Select an option

  • Save harshithjv/c3f8cd90d4ee5428bb8cdb53f3826426 to your computer and use it in GitHub Desktop.

Select an option

Save harshithjv/c3f8cd90d4ee5428bb8cdb53f3826426 to your computer and use it in GitHub Desktop.
Self notes for async handling in python
  • Run via simple await
await async_func()
  • Run via asyncio
import asyncio

asyncio.run(async_func())

Note: Will complete a event loop when asyncio.run is called.

  • Run via asyncio.gather
import asyncio

asyncio.run(asyncio.gather(async_func()))
  • Run via asyncio event loop
import asyncio

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(async_func()))
import asyncio

asyncio.get_event_loop().close()
asyncio.get_event_loop().is_closed() # return True or False. When true old event loop fails stating `RuntimeError: Event loop is closed`

asyncio.set_event_loop(asyncio.new_event_loop())
loop = asyncio.get_event_loop() # or loop = asyncio.new_event_loop() if not calling above line

General references:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment