Events

Jeff Shannon jeff at ccvcorp.com
Fri Nov 19 18:38:21 EST 2004


Terry Reedy wrote:

>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)
>  
>

This bit doesn't actually work.

When event isn't found in self.listeners, you create a new, empty 
list.... but that list is never bound as a value in self.listeners.  And 
even if you add a 'self.listeners = ...' to that line, you'll still have 
the problem that list.append() returns None -- you'll overwrite 
self.listeners with that None.

If you use listeners.setdefault() instead, though, it works just as you 
have it --

 >>> listeners = {}
 >>> listeners.setdefault('OnClick', []).append('foo')
 >>> listeners
{'OnClick': ['foo']}
 >>>

The difference between get() and setdefault() seems to be that get() 
simply returns a sentinel value if the requested key is missing, but 
setdefault() will create a key and assign that  value to it, and then 
return the (default) value of the (new) key.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list