Python Event-Driven Programming
Last Updated :
27 Mar, 2024
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())
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())
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"))
OutputHello 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))
OutputT-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]))
OutputFoo
Bar
End Foo
End Bar
Similar Reads
Python Tips and Tricks for Competitive Programming Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips: Convert
4 min read
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
10 Python Code Snippets For Everyday Programming Problems In recent years, the Python programming language has seen a huge user base. One of the reasons could be that it is easier to learn as compared to other object-oriented programming languages like Java, C++, C#, JavaScript, and therefore more and more beginners who are entering the field of computer s
8 min read
Python for Kids - Fun Tutorial to Learn Python Programming Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzle
15+ min read
Output of Python programs | Set 8 Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) Output: 6Explanation: The beauty of python list datatype is that within a list, a programmer can nest another list,
3 min read
Python Fundamentals Coding Practice Problems Welcome to this article on Python basic problems, featuring essential exercises on coding, number swapping, type conversion, conditional statements, loops and more. These problems help beginners build a strong foundation in Python fundamentals and problem-solving skills. Letâs start coding!Python Ba
1 min read
Interesting Facts About Python Python is a high-level, general-purpose programming language that is widely used for web development, data analysis, artificial intelligence and more. It was created by Guido van Rossum and first released in 1991. Python's primary focus is on simplicity and readability, making it one of the most acc
7 min read
Python Glossary Python is a beginner-friendly programming language, widely used for web development, data analysis, automation and more. Whether you're new to coding or need a quick reference, this glossary provides clear, easy-to-understand definitions of essential Python termsâlisted alphabetically for quick acce
5 min read
Python OOPs Exercise Questions Ready to level up your Python object-oriented programming skills? Explore our collection of Python OOP exercises, packed with over 25 engaging problems to help you master core concepts like encapsulation, inheritance, polymorphism and abstraction. Letâs turn theory into practice!Python OOPs Practice
9 min read
Programming Paradigms in Python Paradigm can also be termed as a method to solve some problems or do some tasks. A programming paradigm is an approach to solve the problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach
4 min read