objects as mutable dictionary keys

Stian Søiland stian at soiland.no
Wed Dec 29 17:56:41 CET 2004

On 2004-12-29 14:04:19, Nick Coghlan wrote:

> This *is* a bug (since Guido called it such), but one not yet fixed as the 
> obvious solution (removing object.__hash__) causes problems for Jython, and 
> a non-obvious solution has not been identified.

class object:
    def __hash__(self):
        # Need to check if our instance has defined some other
        # comparison functions without overloading __hash__ 
        for f in "__cmp__ __eq__".split():
            if not hasattr(self, f):
            # It has the function, but is it the same as in
            # object?
            f1 = getattr(self, f)
            f2 = getattr(object, f)
            if f1.im_func != f2.im_func:
                raise TypeError, "unhashable instance"    
         return id(self)
Of course this won't work, as self.__cmp__ and it's like are so-called 
method-wrapper objects, and I can't immediately see a way to retrieve
the original function behind this.

Also, it might be possible that someone does something like this:

class A(object):
    def __init__(self, use_id=True):
        self.use_id = use_id

    def __eq__(self, other):
        if self.use_id:
            return super(A, self).__eq__(other)
            return something_else

    def __hash__(self, other):
        if self.use_id:
            return super(A, self).__hash__(other)
            return something_else
This will break the object.__hash__  shown above..  What about checking
if __hash__ has been overridden as well, and if so, always return id()?

Stian Søiland               Work toward win-win situation. Win-lose
Trondheim, Norway           is where you win and the other lose.
http://soiland.no/          Lose-lose and lose-win are left as an
                            exercise to the reader.  [Limoncelli/Hogan]
                            Og dette er en ekstra linje 

More information about the Python-list mailing list