why doesn't pop/clear call __delitem__ on a dict?

Daniel Fetchinson fetchinson at googlemail.com
Thu Dec 11 09:30:56 CET 2008

>> I just found out that if I want to have a custom dict it's not enough
>> to overload __getitem__, __setitem__ and __delitem__ because, for
>> example, pop and clear don't call __delitem__. I.e. an instance of the
>> following will not print 'deleted' upon instance.pop( 'key' ):
>> class mydict( dict ):
>>    def __setitem__( self, key, value ):
>>        print 'set'
>>        super( mydict, self ).__setitem__( key, value )
>>    def __getitem__( self, key ):
>>        print 'get'
>>        super( mydict, self ).__getitem__( key )
>>    def __delitem__( self, key ):
>>        print 'deleted'
>>        super( mydict, self ).__delitem__( key )
>> Why is this?
> For optimization purposes essentially, so that the built-in dict can
> be as fast as possible as it is used pervasively in Python.
>> what other methods do I have to overload so that
>> I get what I expect for all dict operations?
> You might consider just subclassing UserDict.DictMixin instead:
> http://docs.python.org/library/userdict.html#UserDict.DictMixin
> It implements the complete dict interface all in terms of provided
> __getitem__(), __setitem__(), __delitem__(), and keys() methods.

Thanks a lot!

Psss, psss, put it down! - http://www.cafepress.com/putitdown

More information about the Python-list mailing list