CodeGym /Java Course /Python SELF EN /Popular asyncio Methods

Popular asyncio Methods

Python SELF EN
Level 25 , Lesson 3
Available

4.1 The run() Method

The asyncio Module provides a bunch of methods and functions for creating and managing asynchronous programs. Here are some of the most popular and commonly used methods and functions of the asyncio module.

Today we'll check out the top 4:

  • run()
  • sleep()
  • wait()
  • gather()

Now for the details:

The asyncio.run(coroutine) Method

This method is used to start an asynchronous program. It's especially handy when you want to run async code from a synchronous context, like from the main thread of the program.

The asyncio.run() method starts the main coroutine and manages the creation and closing of the event loop. This method automatically creates a new event loop and closes it when the coroutine finishes executing.

Signature:


asyncio.run(async_function(), *, debug=False)
        
  • async_function: The coroutine that needs to be executed.
  • debug: An optional parameter that enables debug mode for the event loop.

Usage example:


import asyncio

async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('World')
            
asyncio.run(main())
        

Limitations

Can't be called from inside another event loop:

asyncio.run() should only be called from synchronous code, since it creates and closes its own event loop. Trying to call it from inside an existing event loop will raise an error.

Suitable only for top-level:

This method is meant for running the main entry point of the program and shouldn't be used for nested async function calls.

4.2 The sleep() Method

This method is used when you need to pause the execution of a coroutine for a certain amount of time, without blocking other coroutines.

The asyncio.sleep() method in the asyncio module is used to pause the execution of the current coroutine for a specified number of seconds.

This method differs from the similar time.sleep() method in that it allows other tasks to run during the pause. This makes it useful for writing asynchronous programs that require delays or waits without blocking the main thread.

Signature:


asyncio.sleep(delay, result=None)
        
  • delay: The delay time in seconds (can be a float).
  • result: An optional result that will be returned after the delay is over.

Usage example:


import asyncio

async def main():
    print('Start sleeping')
    await asyncio.sleep(2)
    print('Wake up')
            
asyncio.run(main())
        

In this example, the main coroutine pauses for 2 seconds, allowing other tasks to run during that time, then continues and prints "Wake up".

4.3 The wait() Method

This method is useful when you need to wait for the completion of multiple asynchronous operations, but want more granular control over the waiting process.

The asyncio.wait() method in the asyncio module allows waiting for the completion of multiple asynchronous tasks or coroutines. You can wait for the completion of all tasks, the first completed task, or the completion of any task with an error.

Unlike gather(), the wait() method offers more control over the waiting process, allowing you to specify a timeout and completion conditions.

Key features of the asyncio.wait() method

Signature:


asyncio.wait(fs, *, timeout=None, return_when=ALL_COMPLETED)
        

Where:

  • fs: A collection of Future objects or coroutines that need to be awaited.
  • timeout: An optional parameter specifying the maximum wait time in seconds. If the wait time expires, the method returns the tasks that were completed by that time.
  • return_when: A condition that determines when the method should finish. Possible values:
    • ALL_COMPLETED: The method returns the result when all tasks are completed (default).
    • FIRST_COMPLETED: The method returns the result when the first task is completed.
    • FIRST_EXCEPTION: The method returns the result when any task is completed with an exception.

Waits for the completion of multiple tasks or coroutines. You can specify a wait time and completion conditions.


import asyncio

async def say(what, delay):
    await asyncio.sleep(delay)
    return what
            
async def main():
    task1 = asyncio.create_task(say('hello', 1)) 
    task2 = asyncio.create_task(say('world', 2))
    done, pending = await asyncio.wait([task1, task2], timeout=1.5)
    for task in done:
        print(task.result())
            
asyncio.run(main())
        

In the example above, we wrap each coroutine say() in a Task object using the create_task() method, then pass a list of these tasks to the wait() method. Task objects allow coroutines to run concurrently, not having to wait for one to finish before starting another.

The wait method will wait for the tasks to execute for only a second and a half, then return a tuple of tasks: the first value in the tuple will contain the tasks that were completed (done), the second — those still in progress (pending).

4.4 The gather() Method

This method is particularly useful when you need to run multiple asynchronous operations in parallel and get their results as a list.

The asyncio.gather() method in the asyncio module is used for executing multiple asynchronous tasks concurrently and returning their results as a list. It's a convenient way to group coroutines or tasks and wait for their completion.

Key features of the asyncio.gather() method

Signature:


asyncio.gather(*coros_or_futures, return_exceptions=False)
        

Where:

  • coros_or_futures: Coroutines or Future objects that should be executed.
  • return_exceptions: A boolean value indicating whether exceptions should be returned as results. By default False.

Example usage


import asyncio

async def say_after(delay, what):
    await asyncio.sleep(delay)
    return what
            
async def main():
    results = await asyncio.gather(
        say_after(1, 'hello'),
        say_after(2, 'world')
    )
    print(results)
            
asyncio.run(main())
        

This example shows how asyncio.gather can be used to concurrently execute several tasks, each with its own delay. The results of all tasks are returned as a list. Unlike wait, gather not only waits for the tasks to complete but also collects the results of all coroutines, making it handy for situations where the outcome of each task matters.

2
Task
Python SELF EN, level 25, lesson 3
Locked
Method run()
Method run()
2
Task
Python SELF EN, level 25, lesson 3
Locked
Method sleep()
Method sleep()
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION