Pyventus
Documentation: https://mdapena.github.io/pyventus
Source Code: https://github.com/mdapena/pyventus
Pyventus is a powerful Python package for event-driven programming. It offers a comprehensive suite of tools to easily define, emit, and orchestrate events. With Pyventus, you can build scalable, extensible, and loosely-coupled event-driven applications.
Key Features¶
Pyventus offers several key features, such as:
- Sync and Async Support β Whether your code is synchronous or asynchronous, Pyventus allows you to define event handlers as either sync or async callbacks and emit events from both scopes.
- Customization β Whether you choose official emitters or custom ones, Pyventus allows you to customize the behavior and capabilities of the event emitters to perfectly align with your unique requirements.
- An Intuitive API β Pyventus provides a user-friendly API for defining events, emitters, and handlers. Its design simplifies the process of working with events, enabling you to organize your code around discrete events and their associated actions.
- Runtime Flexibility β Pyventus' runtime flexibility allows you to switch seamlessly between different built-in or custom event emitter implementations on the fly, providing a dynamic and adaptable environment for event-driven programming.
- Reliable Event Handling β Pyventus allows you to define handlers to customize how events are processed upon completion. Attach success and failure logic to take targeted actions based on the outcome of each event execution.
- Scalability and Maintainability β By adopting an event-driven approach with Pyventus, you can create scalable and maintainable code thanks to the loose coupling between its components that enables extensibility and modularity.
- Comprehensive Documentation β Pyventus provides a comprehensive documentation suite that includes API references, usage examples, and tutorials to effectively leverage all the features and capabilities of the package.
Quick Start¶
Pyventus is published as a Python package
and can be installed using pip
, ideally in a virtual environment
for proper dependency isolation. To get started, open up a terminal and install Pyventus with the following command:
Pyventus by default relies on the Python standard library and requires Python 3.10 or higher with no additional dependencies. However, this package also includes alternative integrations to access additional features such as Redis Queue, Celery, and FastAPI. For more information on this matter, please refer to the Optional Dependencies section.
A Simple Example¶
Experience the power of Pyventus through a simple Hello, World!
example that illustrates
the core concepts and basic usage of the package. By following this example, youβll learn how to subscribe to events
and emit them within your application.
Hello, World! Example | |
---|---|
You can also work with async
functions and contexts...
As we can see from the Hello, World!
example, Pyventus follows a simple and intuitive
workflow for defining and emitting events. Let's recap the essential steps involved:
-
Importing Necessary Modules:
We first imported the required modules from Pyventus, which encompassed the
EventLinker
class, theEventEmitter
interface, and theAsyncIOEventEmitter
implementation. -
Linking Events to Callbacks:
Next, we used the
@EventLinker.on()
decorator to define and link the string eventGreetEvent
to the functionhandle_greet_event()
, which will print 'Hello, World!' to the console whenever theGreetEvent
is emitted. -
Instantiating an Event Emitter:
After that, and in order to trigger our event, we needed to create an instance of the event emitter class. While
AsyncIOEventEmitter
was utilized, any built-in or custom implementation could be employed. -
Triggering the Event:
Finally, by using the
emit()
method of the event emitter instance, we were able to trigger theGreetEvent
, which resulted in the execution of thehandle_greet_event()
callback.
Having gained a clear understanding of the workflow showcased in the Hello, World!
example,
you are now well-equipped to explore more intricate event-driven scenarios and fully harness the capabilities of
Pyventus in your own projects. For a deep dive into the package's functionalities, you can refer to the
Pyventus Tutorials or API.
A Practical Example¶
To showcase Pyventus' event-driven capabilities in a real-world scenario, we will explore a practical example of implementing a voltage sensor using an event-driven architecture (crucial for such scenarios). The purpose of this example is to create an efficient voltage sensor that can seamlessly handle real-time data and respond appropriately to specific voltage conditions.
Example β Monitoring Voltage Levels Across Devices (Context)
A common aspect found in many systems is the need to monitor and respond to changes in sensor data. Whether it's pressure sensors, temperature sensors, or other types, capturing and reacting to sensor data is crucial for effective system operation. In our practical example, we will focus on a specific scenario: building a sensor system that monitors voltage levels across devices. The goal of our voltage sensor is to detect potential issues, such as low or high voltage conditions, and respond appropriately in real-time.
To accomplish our goal, we will define a VoltageSensor
class to read voltage levels and emit
events based on predefined thresholds. We will create event handlers to respond to these events, performing actions
such as activating eco-mode for low voltage or implementing high-voltage protection. Additionally, a shared event
handler will provide general notifications for out-of-range voltage situations. The code example below illustrates
the implementation of this system.
As we can see from this practical example, Pyventus enables us to easily build an event-driven system for voltage sensors that is flexible, efficient, and highly responsive. With its intuitive API and support for both synchronous and asynchronous operations, we were able to effectively monitor voltage levels, detect anomalies, and trigger appropriate actions in real-time.
Support for Synchronous and Asynchronous Code¶
Pyventus is designed from the ground up to seamlessly support both synchronous and asynchronous
programming models. Its unified sync/async API allows you to define event callbacks and emit events across
sync
and async
contexts.
Subscribing Event Handlers with Sync
and Async
Callbacks¶
You can optimize the execution of your callbacks based on their workload...
By default, event handlers in Pyventus are executed concurrently during an event emission, running their
sync
and async
callbacks as defined. However, if you have a sync
callback
that involves I/O or non-CPU bound operations, you can enable the force_async
parameter to offload it
to a thread pool, ensuring optimal performance and responsiveness. The force_async
parameter utilizes
the asyncio.to_thread()
function to execute sync
callbacks asynchronously.
Emitting Events from Sync
and Async
Contexts¶
Event propagation within different contexts...
While Pyventus provides a base EventEmitter
class with a unified sync/async API, the
specific propagation behavior when emitting events may vary depending on the concrete EventEmitter
used. For example, the AsyncIOEventEmitter
implementation leverages the AsyncIO
event
loop to schedule callbacks added from asynchronous contexts without blocking. But alternative emitters could
structure propagation differently to suit their needs.
Runtime Flexibility and Customization¶
At its core, Pyventus utilizes a modular event emitter design that allows you to switch seamlessly between different built-in or custom event emitter implementations on the fly. Whether you opt for official emitters or decide to create your custom ones, Pyventus allows you to tailor the behavior and capabilities of the event emitters to perfectly align with your unique requirements.
Swapping Event Emitter Implementations at Runtime¶
By leveraging the principle of dependency inversion and using the base EventEmitter
as a
dependency, you can change the concrete implementation on the fly. Let's demonstrate this using the AsyncIO
Event Emitter and the Executor Event Emitter:
Defining Custom Event Emitters¶
To illustrate Pyventus' customization capabilities, we will define and implement a custom event emitter class for the FastAPI framework. This class will efficiently handle the execution of event emissions through its background tasks workflow.
Official FastAPIEventEmitter
Integration.
In case you're interested in integrating Pyventus with FastAPI, you can refer to the official Pyventus FastAPI Event Emitter implementation.
Event Objects and Global Events¶
In addition to string events, Pyventus also supports Event Objects, which provide a structured way to define events and encapsulate relevant data payloads.
Furthermore, Pyventus provides support for Global Events, which are particularly useful for
implementing cross-cutting concerns such as logging, monitoring, or analytics. By subscribing event handlers to
...
or Ellipsis
, you can capture all events that may occur within that
EventLinker
context.
Global Event Example | |
---|---|
Success and Error Handling¶
With Pyventus, you can customize how events are handled upon completion, whether they succeed or
encounter errors. This customization is achieved by using either the EventLinker's on()
or
once()
decorator within a with
statement block. Inside this block, you can
define not only the event callbacks but also the overall workflow of the event. Now, letβs explore
this simple yet powerful Pythonic syntax of Pyventus through an example.
As we have seen from the example, Pyventus offers a reliable and Pythonic solution for customizing
event handling. By utilizing the EventLinker and its decorators within a with
statement block, we
were able to define the DivisionEvent
and specify the callbacks for division, success, and failure
cases.
Continuous Evolution¶
Pyventus continuously adapts to support developers across technological and programming domains. Its aim is to remain at the forefront of event-driven design. Future development may introduce new official event emitters, expanding compatibility with different technologies through seamless integration.
Current default emitters provide reliable out-of-the-box capabilities for common use cases. They efficiently handle core event operations and lay the foundation for building event-driven applications.
Driving Innovation Through Collaboration
Pyventus is an open source project that welcomes community involvement. If you wish to contribute additional event emitters, improvements, or bug fixes, please check the Contributing section for guidelines on collaborating. Together, we can further the possibilities of event-driven development.
License¶
Pyventus is distributed as open source software and is released under the MIT License.
You can view the full text of the license in the LICENSE
file located in the Pyventus repository.