I am aware of pydispatcher, but there must be other event-related packages around for Python.
Which libraries are available?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.
As of October 2024, these are the event-related packages available on PyPI, ordered by most recent release date.
1.8.2
: May 20240.5.1
: May 20240.11.1
: May 20241.5.0
: April 20242.0.1
: July 20230.5
: July 2023
20205.0
: June 20232.0.7
: February 20230.2.2
: Jun 20230.2.2
: Jun 20231.0.1
: June 20204.0.3
: Jan 20190.2.3a0
: 20180.0.5
: 20182.1.2
: 20170.0.7
: 20161.0
: 20120.3.1
: 2008That's a lot of libraries to choose from, using very different terminology (events, signals, handlers, method dispatch, hooks, ...).
I'm trying to keep an overview of the above packages, plus the techniques mentioned in the answers here.
First, some terminology...
The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern.
Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.
The disadvantage of Observer event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist.
That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).
Might be of interest as well: the Mediator pattern.
A 'hook' system is usally used in the context of application plugins. The application contains fixed integration points (hooks), and each plugin may connect to that hook and perform certain actions.
Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.
Network messaging libraries often use the term 'events' too; sometimes these are similar in concept; sometimes not. They can of course traverse thread-, process- and computer boundaries. See e.g. pyzmq, pymq, Twisted, Tornado, gevent, eventlet.
In Python, holding a reference to a method or object ensures that it won't get deleted by the garbage collector. This can be desirable, but it can also lead to memory leaks: the linked handlers are never cleaned up.
Some event systems use weak references instead of regular ones to solve this.
Observer-style event systems:
list
.set
instead of a list
to store the bag, and implements __call__
which are both reasonable additions.pydispatch.Dispatcher
.Publish-subscribe libraries:
Others:
pytest
plugins.QObject
.