Is Python async or sync?

Mar 24, 2024 ยท 2 min read

New Python developers often get tripped up on the difference between asynchronous and synchronous execution. At a basic level, synchronous execution means code runs sequentially from top to bottom. Each statement waits for the previous one to finish before running.

Asynchronous execution allows statements to run out of order without waiting. This is useful for I/O-bound operations like network requests where your program can do other work while waiting for responses.

Here is some synchronous Python code:

import time

print("Start")
time.sleep(1) 
print("Middle")
time.sleep(1)
print("End")

This runs start, waits 1 second, runs middle, waits 1 second, then runs end.

To make this asynchronous, we use asyncio:

import asyncio

async def main():
    print("Start")
    await asyncio.sleep(1)  
    print("Middle")
    await asyncio.sleep(1) 
    print("End")

asyncio.run(main())

Now instead of blocking, the sleep statements allow other code to run while waiting.

So is Python itself synchronous or asynchronous? The Python language is inherently synchronous, but it enables asynchronous execution through libraries like asyncio. The async/await syntax introduced in Python 3.5 made writing asynchronous code much easier.

Asynchronous programming is essential for building scalable network applications in Python. It helps avoid blocking the main thread while waiting for I/O. However, asynchronous code can be more complex to reason about compared to synchronous code.

Some key takeaways:

  • Synchronous code runs statements sequentially in order
  • Asynchronous code allows statements to run out of order while waiting for I/O
  • Python itself runs synchronously, but asyncio enables asynchronous execution
  • async/await makes asynchronous Python easier to write and read
  • Hope this clears up some common confusion around asynchronous and synchronous programming in Python!

    Browse by tags:

    Browse by language:

    The easiest way to do Web Scraping

    Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


    Try ProxiesAPI for free

    curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    ...

    X

    Don't leave just yet!

    Enter your email below to claim your free API key: