Getting Started¶
This guide walks you through creating your first event dispatcher.
Your First Dispatcher¶
Let’s create a simple example that demonstrates the basic workflow: create a dispatcher, register a listener, and dispatch an event.
from whistle import EventDispatcher
def main():
"""Demonstrate basic synchronous event dispatching."""
# Create an event dispatcher
dispatcher = EventDispatcher()
# Define a listener function
def on_spectacle_starts(event):
print("Please turn down your phones!")
# Register the listener for a specific event
dispatcher.add_listener("spectacle.starts", on_spectacle_starts)
# Dispatch the event
dispatcher.dispatch("spectacle.starts")
if __name__ == "__main__":
main()
Walking Through the Code¶
Import the dispatcher:
from whistle import EventDispatcher
We import
EventDispatcherfor synchronous event handling.Create a dispatcher instance:
dispatcher = EventDispatcher()
Create an instance that will manage events and listeners.
Define a listener function:
def on_spectacle_starts(event): print("Please turn down your phones!")
Listeners are regular Python functions that accept an event parameter.
Register the listener:
dispatcher.add_listener("spectacle.starts", on_spectacle_starts)
Connect the listener to a specific event name.
Dispatch the event:
dispatcher.dispatch("spectacle.starts")
Trigger the event - all registered listeners will be called.
Running the Example¶
Save the code to a file and run it:
python example_01_basic_sync.py
Output:
Please turn down your phones!
Next Steps¶
Now that you understand the basics:
Learn about Synchronous Dispatching for more sync patterns
Explore Asynchronous Dispatching for async/await usage
Discover Listener Priorities to control execution order
Master Event Propagation Control to control event flow