The ABCs of Python: “async,” “await” and feeding the durn cat 

The keywords “async” and “await” were not on the list when I started learning Python. These keywords allow programmers to engage in concurrent computing. I think that means multiple tasks can be run in such a way that they overlap with one another. This stuff is over my head but I’ll take my best whack at it.

This form of computing is based on a “single-threaded, single-process design,” which I believe means that the computer can only do one thing at a time. But even though it does one thing at a time, that doesn’t mean it can’t pop back and forth between different tasks.

Let’s say I get up in the morning and turn on my slow laptop rather than my speedy PC. I hit the start up button and walk away to go start some coffee and then, having started the coffee, I can feed the (acting out) cat, then I go back to the laptop and open the browser, then check on the coffee, then let the (now meowing) cat out, then pour the coffee, then go back to the now functional laptop.

I’m just one person, a single processor. I’m not doing any of these things at the same time (like a parallel computer might). I’m just popping back and forth among different tasks, coming back to the right tasks at the right time.

At least I think that’s about right. Anyway, here’s a very simple application of these key words.

import asyncio

async def hang_on_three_secs():
    print('Hey, just give me three seconds')
    await asyncio.sleep(3)
    print("Okay, I'm back")

This will print out the words, “Hey, just give me three seconds” and then, exactly three second later, will print out “Okay, I’m back.”

For a way more detailed, erudite and probably accurate explanation of these keywords, I recommend RealPython.