What event system for Python do you use? I'm already aware of pydispatcher, but I was wondering what else can be found, or is commonly used?
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 June 2020, these are the event-related packages available on PyPI, ordered by most recent release date.
1.0.1
: June 20200.13.1
: June 2020 (beta)2.0
: Sept 20190.1.2
: Feb 20194.0.3
: Jan 20194.4
: 20180.2.3a0
: 20180.0.5
: 20182.1.2
: 20170.0.7
: 20161.4
: 20152.0.5
: 20150.2.3
: 20141.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
.