async and await

noun

say it: “AY-sink and uh-WAYT” /ˈeɪsɪŋk ænd əˈweɪt/

Python keywords for code that waits: async def makes a function that can pause, and await is where it pauses so other work can run meanwhile.

What do async and await do?

async def makes a function that can pause while it waits for something slow, like a web request. await is where it pauses, letting other work run in the meantime.

import asyncio

async def fetch_weather(city):
    await asyncio.sleep(1)          # pretend web request
    return f"{city}: sunny"

async def main():
    print(await fetch_weather("Denver"))

asyncio.run(main())

In a sentence

  • “The route uses async and await because it waits on httpx calls.”
  • “With async and await, the movie picker asked three services at once instead of one after another.”

Level: Freelancer · More Python terms at this level

Updated