Pythonic event-driven programming.
Project description
Classy Events
Pythonic event-driven programming.
Dependencies
Python 3.8, 3.9
Install
pip install classy-events
Usage
The main ingredient is an event handler instance:
from classy_events import EventHandler
event_handler = EventHandler()
You can register event listeners for events of any type. In this example we use string events. An event listener is a callable, like a function or a method. The registered event handlers for a specific event are called if that event is dispatched by the event handler. Any keyword arguments that accompany the event are passed to the event listeners.
Function listeners
The listener for the event "spam"
, no callbacks needed!
@event_handler.on("spam")
def spam(value):
print(f"on 'spam': '{value}'")
When the "spam"
event is dispatched from anywhere in the code, def spam
will be called:
event_handler.dispatch("spam", value="ham and eggs")
Now on 'spam': 'ham and eggs'
is printed.
Classy listeners
To use instance methods as listeners, only one extra step is needed:
class Spam:
def __init__(self):
event_handler.bind(self)
@event_handler.on("classy_spam")
def spam(self, value):
print(f"on '{type(self).__name__}.spam': '{value}'")
spam_instance = Spam()
In __init__
, the instance is bound to the handler. Note that this
event_handler.bind
call is not required to be within the __init__
.
To see this in action, we dispatch the "classy_spam"
event:
event_handler.dispatch("classy_spam", value="the classiest")
And we see the output on 'Spam.spam': 'the classiest'
.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file classy-events-0.3.0.tar.gz
.
File metadata
- Download URL: classy-events-0.3.0.tar.gz
- Upload date:
- Size: 9.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.22.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.53.0 CPython/3.8.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f0551476c9b41575b2c10aecf52f296c484f8d435c56d7a0edde903d3795e5ee |
|
MD5 | d0934a4d6b396d0a5663e7a0a916685c |
|
BLAKE2b-256 | ac87f2f8753e5805afe1af8bf1225eeab3e4ee100a124df98be3a824f2c09b91 |
File details
Details for the file classy_events-0.3.0-py3-none-any.whl
.
File metadata
- Download URL: classy_events-0.3.0-py3-none-any.whl
- Upload date:
- Size: 21.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.6.1 requests/2.22.0 setuptools/50.3.2 requests-toolbelt/0.9.1 tqdm/4.53.0 CPython/3.8.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 580b9883ba305764c152bacf536fa1aae88fcb17b4686efdb6cb1389be33b521 |
|
MD5 | c946d1d010f753ce028578de7ce0d6aa |
|
BLAKE2b-256 | 49ac283dded0651641d280387bf46bb9cacddfd635c3b0c217a3e2c9ed962c81 |