key - key pairs

Paul McGuire ptmcg at austin.rr.com
Fri Jun 24 21:09:41 CEST 2005


Man, this is not my week!  Another bug in my posted code!  The posted
version of SymmetricDict fails when adding an entry in which the key
equals the value.  First bug is in __setitem__ in which the insertion
is done twice, which is wasteful but benign.  The second bug is in
__delitem__, which throws an exception when we try to delete the
back-pointing entry - which was already deleted since there is only one
entry.

Another cautionary tale on the value of testing...

Here it the improved SymmetricDict code.

-- Paul


class SymmetricDict(dict):
    def __delitem__(self,k):
        v = self[k]
        super(SymmetricDict,self).__delitem__(k)
        if not v==k:
            super(SymmetricDict,self).__delitem__(v)

    def __setitem__(self,k,v):
        if k in self:
            del self[k]
        if v in self:
            del self[v]
        super(SymmetricDict,self).__setitem__(k,v)
        if not v==k:
            super(SymmetricDict,self).__setitem__(v,k)




More information about the Python-list mailing list