Python await Keyword
The Python await keyword is used to pause a coroutine. The coroutine is a function with the ability to pause its execution when encountering an operation that may take a while to complete.
When the long-running operation completes, we can resume the paused coroutine and execute the remaining code in that coroutine.While the coroutine is waiting for the long-running operation, we can run other code. By doing this, we can run the program asynchronously to improve its performance.
Syntax
Following is the syntax of the Python await keyword −
await
Example
Following is an basic example of the Python await keyword −
import asyncio
# Define the asynchronous function
async def cube(number):
return number * number * number
# Main function to run the coroutine
async def main():
# Await the result of the cube function
result = await cube(10)
print(result)
# Run the main function
asyncio.run(main())
Output
Following is the output of the above code −
1000
Using 'await' with sleep()
The sleep() is used to pause the execution for mentioned section. It accepts an integers value.
Example
Here, we have paused the function for one second using sleep() and await keyword −
import asyncio
async def say_hello():
print("Hello!")
await asyncio.sleep(1) # Pauses the execution for 1 second
print("World!")
async def main():
print("Start")
await say_hello() # Waits for the say_hello coroutine to complete
print("End")
# Run the main coroutine
asyncio.run(main())
Output
Following is the output of the above code −
Start Hello! World! End
python_keywords.htm