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.
SyntaxFollowing is the syntax of the Python async keyword −
asyncExample
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 awaitedUsing 'async' by importing asyncio
We can use the async by importing asyncio module.
ExampleHere, 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4