Open In App

Python Event-Driven Programming

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Event-driven programming is a powerful paradigm used in Python for building responsive and scalable applications. In this model, the flow of the program is driven by events such as user actions, system notifications, or messages from other parts of the program. In this article, we will learn about event-driven programming in Python.

What is Python Event-Driven Programming?

Python’s event-driven programming model revolves around the concept of an event loop. An event loop continuously monitors events and dispatches them to the appropriate event handlers. This allows the program to efficiently handle multiple asynchronous tasks concurrently.

Asyncio – Python Event-Driven Programming Module

In the asyncio module of Python, several key concepts are used to facilitate event-driven programming:

Python Event-Driven Event Loop

The event loop (asyncio.get_event_loop()) is the central component that orchestrates the execution of asynchronous tasks and handles events. In this example, we define a coroutine main() that prints “Hello”, waits for 1 second asynchronously, and then prints “World”. We use asyncio.run() to execute the coroutine within the event loop.

Python3
import asyncio

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

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Output
Hello
World

Python Event – Driven Futures

Futures (asyncio.Future) represent the result of an asynchronous operation. They allow you to track the status of asynchronous tasks and retrieve their results when they are complete. In this example, we create a future object and set its result asynchronously after 1 second. We then await the future to retrieve its result and print it.

Python3
import asyncio


async def main():
    await asyncio.sleep(1)
    return "Hello"

loop = asyncio.get_event_loop()
future = asyncio.ensure_future(main())

loop.run_until_complete(future)
print("Result:", future.result())

Output
Result: Hello

Python Event-Driven Coroutines

Coroutines are special functions defined with the async def syntax. They can be paused and resumed asynchronously, allowing for non-blocking execution of code. In this example, we define a coroutine greet() that prints a greeting, waits for 1 second asynchronously, and then says goodbye. We use asyncio.gather() to concurrently execute multiple coroutines.

Python3
import asyncio

async def greet(name):
    print("Hello", name)
    await asyncio.sleep(1)
    print("Goodbye", name)

loop = asyncio.get_event_loop()
loop.run_until_complete(greet("Alice"))

Output
Hello Alice
Goodbye Alice

Python Event-Driven @asyncio.coroutine Decorator:

The @asyncio.coroutine decorator is used to define legacy-style coroutines that are compatible with older versions of Python. This code demonstrates the use of the @asyncio.coroutine decorator to define a coroutine. The countdown() coroutine prints a countdown message every second using yield from asyncio.sleep(1).

Python3
import asyncio


@asyncio.coroutine
def countdown(n):
    while n > 0:
        print("T-minus", n)
        yield from asyncio.sleep(1)
        n -= 1


loop = asyncio.get_event_loop()
loop.run_until_complete(countdown(3))

Output
T-minus 3
T-minus 2
T-minus 1

Python Event-Driven Tasks

Tasks (asyncio.Task) are used to schedule and manage coroutines within the event loop. They represent asynchronous units of work and allow for better control over execution. Here, we create two coroutines foo() and bar() representing two asynchronous tasks. We use loop.create_task() to create Task objects for each coroutine and run them concurrently using asyncio.wait().

Python3
import asyncio

async def foo():
    print("Foo")
    await asyncio.sleep(1)
    print("End Foo")

async def bar():
    print("Bar")
    await asyncio.sleep(2)
    print("End Bar")

loop = asyncio.get_event_loop()
task1 = loop.create_task(foo())
task2 = loop.create_task(bar())

loop.run_until_complete(asyncio.wait([task1, task2]))

Output
Foo
Bar
End Foo
End Bar


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads