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.
Join the DZone community and get the full member experience.
Join For FreeThe ‘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.
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."
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.
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:
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,
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.
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.
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.
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
Opinions expressed by DZone contributors are their own.
Comments