Python function (with examples)

Updated: July 10, 2023 By: Khue Post a comment


The function was introduced in Python 3.7 (which was released in 2018). It is a high-level API that creates an event loop, runs the coroutine in the event loop, and finally closes the event loop when the coroutine is complete. It returns the final result of the coroutine or raises an exception if the coroutine fails.

Syntax:, *, debug=False)


  • coro is a coroutine object that you want to run in an event loop. A coroutine is a special kind of function that can pause and resume its execution using the async and await keywords.
  • debug is an optional keyword argument that controls the debug mode of the event loop. If True, the event loop will log more information, check for common errors, and enable the asyncio.debugger module. The default value is False.

It is recommended to use the function as the main entry point for asyncio programs unless you need more fine-grained control over the event loop.


Running a Simple Coroutine

A simple program that prints two parts of a sentence with a delay between:

import asyncio

async def main():
    print('Welcome to ...')
    await asyncio.sleep(3)
    print('... Sling Academy!')

Asynchronous I/O

This example demonstrates using to handle asynchronous I/O operations. It is useful for performing I/O-bound operations concurrently, improving efficiency by not blocking the event loop while waiting for I/O operations to complete.

import asyncio

async def download_file(url):
    # Simulate file download
    await asyncio.sleep(3)
    print(f"Successfully downloaded file from {url}")

async def main():
    tasks = [

    await asyncio.gather(*tasks)

In the code above, the download_file() coroutine uses asyncio.sleep() to simulate file downloads. In the main() coroutine, we create tasks for each file download and await their completion using asyncio.gather().

Notify of
Inline Feedbacks
View all comments