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

Daniel Fetchinson fetchinson at googlemail.com
Thu Dec 11 02:53:28 EST 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? There might other gotchas too I suppose. My intention is
clear from the above, what other methods do I have to overload so that
I get what I expect for all dict operations?

Cheers,
Daniel

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



More information about the Python-list mailing list