This code creates a singleton event dispatcher. It's called like this:

eventDispatcher = Event()
eventDispatcher.on("event", handler)
eventDispatcher.trigger("event", 5)

I'm wondering if this is "the python way," or if it could be improved? Especially the class, I'm not sure about creating a new object for every use of the dispatcher.

class Event():
    events = {}

    def on(self, event, func):
        if event not in self.events.keys():
            self.events[event] = []


    def trigger(self, event, *args, **namedArgs):
        if event in self.events.keys():
            for func in self.events[event]:
                func(*args, **namedArgs)

Checking items in dictionnary

There is no need to call keys when checking for dictionnary membership. Much like there is no need of True in if my_bool == True.


Checking if a key exist and set it to a default value otherwise is so common that you have 2 standard ways of doing it: dict.setdefault(...) or using a collections.defaultdict.


Since KeyError should normaly not happen, you can use EAFP approach by using try...except instead of if. It's a tiny bit faster if exceptions are quite rare. Moreover, by using defaultdict you are guaranteed that every access to an item will be valid, thus eliminating the need to check membership of any key.


Since the only state you need is the one of the class, and in order to avoid instanciating to call methods, you can use @staticmethods and call them with Event.on(...) and Event.trigger(..).

Proposed alternative

from collections import defaultdict

class Event():
    __events = defaultdict(list)

    def on(event, func):

    def trigger(event, *args, **namedArgs):
        for func in Event.__events[event]:
            func(*args, **namedArgs)
| improve this answer | |
  • 1
    \$\begingroup\$ Is there a reason two underscores are used with the events variable? (Rather than just one.) \$\endgroup\$ – jayshua Nov 3 '15 at 13:47
  • 1
    \$\begingroup\$ @jayshua It is to trigger name mangling to better emphasize that anything related to __events is Event's business. You can use one or no underscore if you see fit. \$\endgroup\$ – 301_Moved_Permanently Nov 3 '15 at 14:21

Very minor note, but the normal Python names are args and kwargs (ie. Keyword Arguments).

def trigger(self, event, *args, **kwargs):
| improve this answer | |
  • \$\begingroup\$ This should be a comment to the previous answer—not posted as its own answer. \$\endgroup\$ – Zearin Nov 25 '15 at 16:05
  • 1
    \$\begingroup\$ @Zearin It's not related to the other answer, it's a separate note. \$\endgroup\$ – SuperBiasedMan Nov 25 '15 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.