Explain Codes LogoExplain Codes Logo

Asynchronous method call in Python?

python
asyncio
threading
multiprocessing
Anton ShumikhinbyAnton Shumikhin·Jan 27, 2025
TLDR

To implement an asynchronous operation in Python, utilize the async and await keywords in association with the asyncio module, like this:

import asyncio async def async_task(): print('Async task started, like the hustle and bustle in a beehive🐝.') await asyncio.sleep(1) # Simulates a non-blocking delay — like making a cup of coffee ☕︎. print('Async task finished, as smooth as a cappuccino.') # Kick-starting the asynchronous task: async def main(): await async_task() # Now fuel-up the asyncio engine! asyncio.run(main())

Here, asyncio.run(main()) is the starting point. main triggers the async_task method. The keyword await calls other async methods or performs awaitable asyncio operations, promoting non-blocking and concurrent execution.

Async: Beyond the basics

Beyond async/**await**, let's explore threading and multiprocessing. Each works a bit differently when handling asynchronous calls — like different superheroes with unique superpowers!

Threading - The Flash⚡ for IO-bound tasks

Just like how The Flash can run super-fast, threading in Python is ideal for speedy IO-bound operations. This way, your program can also do other tasks while waiting on IO operations (don't we wish we could multitask like that?). Here's how to implement it:

import threading def async_thread_target(): print("Doing an IO-bound operation here. Like reading a pretentious novel...") thr = threading.Thread(target=async_thread_target) thr.start() # Engines on, let's hit the gas! thr.join() # Stay till the end. Or else, you'll never know who did it!

thr.start() activates the thread, and thr.join() waits for it to finish. For suspense, you can use thr.is_alive() to see if the thread's keeping us on edge.

Multiprocessing - Hulk💪 for CPU-bound tasks

If you have CPU-bound tasks, call up the Hulk — the multiprocessing module leverages multiple processors faster than you can say "SMASH!" You can use multiprocessing.Pool.apply_async for async method calls like this:

from multiprocessing import Pool def async_process_target(arg): print(f"Function Process Number: {arg} reporting like a boss.") return arg * arg if __name__ == '__main__': pool = Pool() result = pool.apply_async(async_process_target, (2,)) print(result.get()) # The package has arrived, sir!

Choosing your Superpower

Having trouble deciding between asyncio, threading, and multiprocessing? Let's travel a bit deeper into when to use them — it's like choosing the perfect superpower!

When to use asyncio

  • IO-bound and high-level structured network code.
  • You need to deal with many concurrent connections — like a switchboard operator.

When to use threading

  • IO-bound tasks that require waiting, such as reading from or writing to a disk.
  • Threads provide a shared memory space, but remember about the GIL (Global Interpreter Lock).

When to use multiprocessing

  • CPU-bound tasks.
  • It offers the glory of parallelism across multiple CPUs.

Enter, Twisted

The Twisted library, not Python's core, but a jedi master of asynchronous programming. Twisted uses Deferred objects for handling callbacks like a cat with a laser pointer:

from twisted.internet.defer import Deferred def callback(result): print(f"Received callback: {result} like a surprise pizza delivery 🍕") deferred = Deferred() deferred.addCallback(callback) deferred.callback("Echo from Twisted!")

With Twisted, you can add multiple callbacks and error handlers. This library maturely handles network apps needing non-blocking responses.

Asyncio's Event Loops and Timers

Asyncio provides event loops and timers for better control over asynchronous executions:

async def periodic(): while True: print('Periodic task running like a grandfather clock.') await asyncio.sleep(2) # Ticking every 2 seconds loop = asyncio.get_event_loop() loop.run_until_complete(periodic())

Here, loop.run_until_complete() runs tasks until they finish, and asyncio.sleep() introduces paws, I mean, pauses.