DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Mastering Exception Handling in Java CompletableFuture: Insights and Examples
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • DuckDB for Python Developers
  • Building a Production-Ready AI Agent in 2026: Beyond the Hello World Demo

Trending

  • Why AI-Generated Code Breaks Your Testing Assumptions
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • S3 Vectors: How to Build a RAG Without a Vector Database
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  1. DZone
  2. Coding
  3. Languages
  4. Demystifying Basics of Async/Await in Python

Demystifying Basics of Async/Await in Python

In this article learn more about async/await functions and how to use these functions in Python code.

By 
Sameer Shukla user avatar
Sameer Shukla
DZone Core CORE ·
Jan. 14, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
4.3K Views

Join the DZone community and get the full member experience.

Join For Free

The ‘asyncio’ is a Python module that provides support for writing asynchronous code using the async/await syntax. It is designed to handle asynchronous I/O operations efficiently, making it well-suited for building concurrent and scalable applications.

Understanding ‘Async’

In Python, the 'async' keyword helps in defining the asynchronous functions or coroutines. The foundation of 'asyncio' module relies on these coroutines, which are like special functions whose execution can pause and let another coroutine take over for processing. When we add the 'async' keyword before a function, the regular function transforms into a coroutine ‘async def fetch():’

Let's grasp the difference in the execution of synchronous and asynchronous functions.

Python
 
def fetch():
    return "Hello World" 

print(fetch()) # Hello World


In this scenario, synchronously calling the fetch() function results in the immediate return of the string "Hello World."

Python
 
async def fetch():
     return “Hello World”

print(fetch()) # <coroutine object fetch at 0x7fdf620994d0>


When we mark the ‘fetch()’ function asynchronous with the 'async' keyword, calling it returns a coroutine object rather than the actual result as printed by the above program. Remember, the coroutine needs to be awaited to retrieve the value it produces.

Python
 
async def fetch():
    return "Hello World"

print(await fetch()) # Hello World

Understanding ‘Await’

The ‘await’ is used with coroutines to pause the execution of it until the awaited asynchronous operation is complete. When we use await, the control moves from one coroutine to another, for ex: 

Python
 
async def fetch():
    print('Hello World')
    await asyncio.sleep(4)
    print("Hello World Again")


 In the ‘fetch’ coroutine, once "Hello World" is printed, the control transitions to the sleep coroutine, causing the execution to pause for 4 seconds before printing "Hello World Again". The complete program looks like, 

Python
 
import asyncio

async def fetch():
    print('Hello World')
    await asyncio.sleep(4)
    print("Hello World Again")


async def main():
    await fetch()

if __name__ == "__main__":
    asyncio.run(main())

Error Handling

Coroutines can handle errors using standard try-except blocks. Exceptions within coroutines can be caught and processed just like in synchronous code.

Python
 
import asyncio


async def fetch_server_data():
    raise ValueError("Simulated network error")


async def fetch():
    print('Hello World')
    try:
        await fetch_server_data()
    except ValueError as e:
        print(f"Error fetching data: {e}")


async def main():
    await fetch()


if __name__ == "__main__":
    asyncio.run(main())

Timeouts and Delays

'asyncio' allows you to set timeouts for coroutines or delay their execution using functions like 'asyncio.sleep' and 'asyncio.wait_for'.

Timeouts are limits set on the duration allowed for the completion of a particular asynchronous operation or coroutine. If the operation takes longer than the specified timeout, 'asyncio' can raise an exception, allowing the program to respond appropriately.

Python
 
import asyncio


async def fetch_server_data():
    await asyncio.sleep(4)
    return "Done Processing"


async def fetch():
    try:
        await asyncio.wait_for(fetch_server_data(), timeout=2.0)
    except TimeoutError as e:
        print(f"Error fetching data: {e}")


async def main():
    await fetch()


if __name__ == "__main__":
    asyncio.run(main())


In this example, asyncio.wait_for function is used to set a timeout of 2 seconds for the fetch_server_data function to respond.  If the fetch_server_data operation takes longer than 2 seconds, a TimeoutError is caught, and an error message is printed.

Delays involve intentionally pausing the execution of a coroutine for a specified duration before proceeding. The asyncio.sleep function is commonly used to introduce delays within asynchronous code.

Python
 
import asyncio

async def fetch()
    print("Start of operation")
    await asyncio.sleep(2)  # Pause for 2 seconds
    print("End of operation after delay")

await fetch()

Here, asyncio.sleep(2) introduces a delay of 2 seconds within the fetch() coroutine

Error message Python (language) Timeout (computing) Asynchronous method invocation

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Exception Handling in Java CompletableFuture: Insights and Examples
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • DuckDB for Python Developers
  • Building a Production-Ready AI Agent in 2026: Beyond the Hello World Demo

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook