Async in Python

Who can wait quietly while the mud settles?
Who can remain still until the moment of action?

Laozi, Tao Te Ching

What is async in general?

You go to the doctor. You take the appointment. Either you wait in the queue idle or take out your laptop and start trading in the meantime (if you are a trader). The second options is an async way of doing things, where you don’t do things sequentially wherein u suffer with resource idleness and non-premptivness

Another analogy based explanation here -> link

Another example would be the way Vishwanathan Anand played chess against multiple players at the same time.

But python is single-threaded, how do we achieve async?

Async has nothing to do with multi-threading. In an async environment, a single process thread runs all the time, but it may, for event-driven reasons switch from one function to another.

Any drawbacks?

They might be some race conditions, since the order in which events are being handled is not under us. However they can be managed using low level apis.

Lets understand few common terms in async programming in python.

async def g():
# Pause here and come back to g() when f() is ready
r = await f()
return r

When our python process encounters await f(), the event loop is notified to stop further execution of g() and wait till f() returns.

Writing our first async code in Python

Our hero - Asyncio

import asyncioasync def main():
print("hello")
await asyncio.sleep(1)
print("world")
asyncio.run(main())

Once asyncio.run(main()) is called

Note: If you try running asyncio.run(function) in Jupyter notebook, it will throw a Runtime exception. Rather just go ahead with await(function), reason being jupyter notebook internally starts an event loop upon bootstrapping.

Interesting topics to explore in this section would be Futures, Generator based coroutines, Asyncio Design Patterns, Queues etc.

Thank you for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store