[Python-Dev] For Python 3k, drop default/implicit hash, and comparison

Josh Hoyt josh at janrain.com
Sun Nov 6 22:57:34 CET 2005

On 11/6/05, Guido van Rossum <guido at python.org> wrote:
> On 11/6/05, Phillip J. Eby <pje at telecommunity.com> wrote:
> > When I use this pattern, I often just include the object's type in the
> > key.  (I call it the 'hashcmp' value, but otherwise it's the same pattern.)
> But how do you make that work with subclassing? (I'm guessing your
> answer is that you don't. :-)

If there is a well-defined desired behaviour for comparisons in the
face of subclassing (which I'm not sure if there is) then that
behaviour could become part of the definition of how __key__ works.
Since __key__ would be for clarity of intent and convenience of
implementation, adding default behaviour for the most common case
seems like it would be a good idea.

My initial thought was that all subclasses of the class where __key__
was defined would compare as equal if they return the same value. More
precisely, if two objects have the same __key__ method, and it returns
the same value, then they are equal. That does not solve the __cmp__
problem, unless the __key__ function is used as part of the ordering.

For example:

def getKey(obj):
    __key__ = getattr(obj.__class__, '__key__')
    return (id(key), key(obj))

An obvious drawback is that if __key__ is overridden, then the
subclass where it is overridden and all further subclasses will no
longer have equality to the superclass. I think that this is probably
OK, except that it may be occasionally surprising.


More information about the Python-Dev mailing list