Updated June 19, 2023
Introduction to Python Async
Python async is an asynchronous function or also known as coroutine in Python changes the behavior of the function call. Async in Python is a feature for many modern programming languages that allows the functioning of multiple operations without waiting time. This is a smart way to handle multiple network tasks or I/O tasks where the actual program’s time is spent waiting for other tasks to finish. We shall look into async implementation in Python. Moving to async functions not only required knowledge of Syntax but also a way of thinking for the logic needs to be changed.
Syntax:
Asynchronous functions/ Coroutines use async keyword OR @asyncio.coroutine.
Either function would work as a coroutine which returns coroutine objects. Calling either function would not actually run, but a coroutine object is returned.
In some cases, if needed to determine whether the function is a coroutine or not, asyncio has a method asyncio.iscoroutinefunction(func). If the user wants to determine whether the object returned from the function is a coroutine object, they can utilize the asyncio method asyncio.iscoroutine(obj).
Defining async def makes a coroutine
Python Async provided single-threaded concurrent code by using coroutines, running network I/O, and other related I/O over sockets. Python async has an event loop that waits for another event to happen and acts on the event.
Async provides a set of Low Level and High-Level API’s
- To create and maintain event loops providing asynchronous API’s for handling OS signals, networking, running subprocesses, etc.
- Perform network I/O and distribute tasks in the mode of queues.
- Implement protocols using transport and synchronize concurrent code.
- Bridges call back-based libraries and code with async or await
- Runs coroutines concurrently with full control of their execution.
Examples of Python Async
Lets us discuss the examples of Python Async.
Example #1
Code:
import queue
def task(name, sample_queue):
if sample_queue.empty():
print(f'Task {name} has nothing to do')
else:
while not sample_queue.empty():
cnt = sample_queue.get()
total = 0
for x in range(cnt):
print(f'Task {name} is running now')
total += 1
print(f'Task {name} is running with a total of: {total}')
def sample_async():
sample_queue = queue.Queue()
for work in [2, 5, 10, 15, 20]:
sample_queue.put(work)
tasks = [
(task, 'Async1', sample_queue),
(task, 'Async2', sample_queue),
(task, 'Async3', sample_queue)
]
for t, n, q in tasks:
t(n, q)
if __name__ == '__main__':
sample_async()
Output:
‘task’ in the above example accepts string and queue.
Example #2
Code:
import asyncio
import functools
def event_handler(loop, stop=False):
print('Calling event handler')
if stop:
print('Loop is being stopped')
loop.stop()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
try:
loop.call_soon(functools.partial(event_handler, loop))
print('Loop is being started')
loop.call_soon(functools.partial(event_handler, loop, stop=True))
loop.run_forever()
finally:
print('Loop is being closed')
loop.close()
Output:
Example #3
Code:
import asyncio
async def sample_task(task_seconds):
print('Task takes {} seconds to complete'.format(task_seconds))
await asyncio.sleep(task_seconds)
return 'task has been completed'
if __name__ == '__main__':
sample_event = asyncio.get_event_loop()
try:
print('Creation of tasks started')
task_object_loop = sample_event.create_task(sample_task(task_seconds=3))
sample_event.run_until_complete(task_object_loop)
finally:
sample_event.close()
print("Task status: {}".format(task_object_loop.result()))
Output:
On running the Program,
As the task takes 3 seconds to complete, so after completion of the task,
Python Async is a function used for concurrent programming for single code to be executed independently.
Example #4
Code:
import asyncio
async def sample_task(task_seconds):
print('Task takes {} seconds to complete'.format(task_seconds))
await asyncio.sleep(task_seconds)
return 'task has been completed'
if __name__ == '__main__':
sample_event = asyncio.get_event_loop()
try:
print('Creation of tasks started')
task_object_loop = sample_event.create_task(sample_task(task_seconds=3))
sample_event.run_until_complete(task_object_loop)
finally:
sample_event.close()
print("Task status: {}".format(task_object_loop.result()))
Output:
Event loop countdown() coroutine calls, executes until yield from, and asyncio.sleep() function. The future loop watches the future object until the other one is over. Once the second one is on, the event loop gets the paused countdown coroutine(), which gives the event loop the future object and sends future objects to result back to the coroutine with countdown() starting running back.
Asyncio was added to the standard library to prevent looping. Running event loops provides a few features, like,
- Registering, executing, and canceling delayed calls i.e. Asynchronous functions.
- Creation of subprocesses and transports for communication between tasks.
- Creations of client and server transport for communication between tasks.
- Delegating function calls to thread pools.
The reason behind using async is to improve the throughput of the program by reducing idle time when performing I/O. Programs in this juggle use an abstraction event loop. Resemble multi-threading, but event loop generally lives in a single thread.
With this, we conclude ‘Python Async.’ Async I/O is a language-agnostic model and lets coroutines communicate with each other. Asyncio, a Python function, provides API to run and manage coroutines. API of asyncio was declared stable rather being provisional. In Python, async has evolved with minor changes in the versions. Using Python async tool, asynchronous programming is powerful. Based on users’ requirements, Python async achieves concurrency, code flow, architecture design, and data manipulation. However, if a user tries to implement a program or a server that implements significant I/O operations, async makes a huge difference.
Thanks! Happy Learning!!
Recommended Articles
This is a guide to Python Async. Here we discuss an introduction, syntax, and examples with code implementation. You can also go through our other related articles to learn more –