In event-driven programming, events are defined as occurrences or changes in state that trigger responses within an application. They are essential for enabling communication between different components, acting as messages that convey important information and enable dynamic responses.
String events are defined by a string name and are among the simplest types of events to use. They offer a straightforward approach for handling events, making them ideal for basic use cases. However, because they are hardcoded and lack a structured format, they may not be suitable for more complex scenarios.
To pass data to subscribers in string-based events, simply define parameters in the callback function you are subscribing to, and when emitting the string event with an event emitter, provide the necessary values using the *args and **kwargs arguments.
Event Objects are essentially events that are defined through data classes. This event type not only offers a structured way to define events and encapsulate relevant data payloads, but also provides support for additional validations and behaviors.
fromdataclassesimportdataclassfrompyventus.eventsimportAsyncIOEventEmitter,EventEmitter,EventLinker@dataclass# Define a Python dataclass to represent an event and its payload.classOrderCreatedEvent:order_id:intpayload:dict@EventLinker.on(OrderCreatedEvent)# Use the event class to attach subscribers.defhandle_order_created_event(event:OrderCreatedEvent):# The event instance is automatically passed as the first argument.# In methods with self or cls, the event is passed after those arguments.print(f"Event Object: {event}")event_emitter:EventEmitter=AsyncIOEventEmitter()event_emitter.emit(event=OrderCreatedEvent(# (1)!order_id=6452879,payload={},),)
You can also emit the event object as a positional argument:
To ensure that the payload of an event meets a specific criteria before its propagation, you can use the dataclasss' method __post_init__() to implement the necessary validation logic.
@dataclassclassOrderCreatedEvent:order_id:intpayload:dictdef__post_init__(self):ifnotisinstance(self.order_id,int):raiseValueError("Error: 'order_id' must be a valid int number!")ifnotself.payload:raiseValueError("Error: 'payload' cannot be empty!")
In addition to event objects, Pyventus allows exceptions to be treated as first-class events. This enables the propagation and handling of errors in an event-driven manner.
Pyventus also provides support for global events, which are particularly useful for implementing cross-cutting concerns such as logging, monitoring, and analytics. By subscribing event callbacks to ..., you can capture all events that may occur within that specific EventLinker context.
If you wish to support additional event type definitions, such as defining event objects using Pydantic's BaseModel, you only need to create a custom EventLinker and modify the get_valid_event_name() class method. Once you've done that, ensure that you utilize this custom EventLinker throughout your application.