Open In App

Mimicking Events in Python

Last Updated : 31 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

First and foremost, What are events? 
Events are the constructs that enable a class to notify other classes when something of interest takes place. 
In the layman language, it is basically similar to raising a flag to signal others that something of interest has happened.
 

When to use events in Python?

Event-based programming is predominantly used while working with UI(user interface) where different components need to be signalled of some occurrence. for e.g imagine a Currency Converter that needs to output the converted currency in box2 while the user enters some value in box1. 
How does box2 get to know that the user has entered something in box1 and what needs to be done in the response to it.
This is one of the most basic examples of event-based programming.
Another possible example could be the HomeSecurity System where some possible actions such as the alarm need to be raised, the message needs to be sent to the owner and the Police need to be informed about the possible theft are to be performed on the breach of the lock. These types of systems can be easily designed using the event-based mechanism where the event will be raised as soon as someone breaks the lock and in turn notifying the event handlers to play their part.
Now, in this post, we will use the latter example to understand how such events can be designed in Python where it is not supported by default.
 

Python3





Output: 
 

police have been informed
owner has been messaged about the possible theft
Alarm has started

The class that raises the event is called the publisher and the classes that receive the event are called subscribers. 
Also, an event can have multiple subscribers and a subscriber can handle multiple events from multiple publishers

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads