Events

Terry Reedy tjreedy at udel.edu
Fri Nov 19 17:04:19 EST 2004


"factory" <t at t.com> wrote in message 
news:MPG.1c08708d5ec6746c989688 at news-server...
>  Anyone want to comment on what they think of this following bit of a
> simple event framework?

Since there can be multiple listeners for a particular type of event, I 
would use an event-listener dict with event as key and list of listeners as 
the value.  This simplifies the code.  Plus, linearly scanning a list of 
event listener pairs to respond to an event (or deregister) will bite when 
the list gets long enough.  So, in __init__,
    self.listeners = {}

For AddListener, the handy idiom for appending a new listener to a possibly 
non-existent list of current listeners is
    self.listeners.get(event, []).append(listener)
(If you cannot other wise guarantee that listeners only try to register for 
a particular event once, you might want to add a check here.)

The body of Talk is then the much simpler
        for listener in self.listeners[event]:
                listener( *args )

If you can guarantee that listeners are only registered once for an event, 
then deletion is also simple: self.listeners[event].remove(listener)

Terry J. Reedy







More information about the Python-list mailing list