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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Exception Handling in Java CompletableFuture: Insights and Examples
  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • How AI Agents Are Transforming Enterprise Automation Architecture
  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
3.7K 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
  • Start Coding With Google Cloud Workstations
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Why I Started Using Dependency Injection in Python

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!