Python async Keyword
The Python async keyword is used to create a coroutine. The coroutine is a regular 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 async keyword −
async
Example
Following is an basic example of the Python async keyword −
async def cube(number):
return number*number*number
result = cube(10)
print(result)
Output
Following is the output of the above code −
<coroutine object cube at 0x7eacc6c87040> sys:1: RuntimeWarning: coroutine 'cube' was never awaited
Using 'async' by importing asyncio
We can use the async by importing asyncio module.
Example
Here, we have defined coroutine functions by async keyword and paused the function for two seconds by using await keyword −
import asyncio
async def greet(name):
print(f"Hello, {name}")
await asyncio.sleep(2)
print(f"Goodbye, {name}")
async def main():
await asyncio.gather(
greet("Alice"),
greet("Bob"),
greet("Charlie")
)
# Run the main coroutine
asyncio.run(main())
Output
Following is the output of the above code −
Hello, Alice Hello, Bob Hello, Charlie Goodbye, Alice Goodbye, Bob Goodbye, Charlie
python_keywords.htm