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

Guido van Rossum guido at python.org
Sun Nov 6 21:58:57 CET 2005


On 11/6/05, John Williams <jrw at pobox.com> wrote:
> (This is kind of on a tangent to the original discussion, but I don't
> want to create yet another subject line about object comparisons.)
>
> Lately I've found that virtually all my implementations of __cmp__,
> __hash__, etc. can be factored into this form inspired by the "key"
> parameter to the built-in sorting functions:
>
> class MyClass:
>
>    def __key(self):
>      # Return a tuple of attributes to compare.
>      return (self.foo, self.bar, ...)
>
>    def __cmp__(self, that):
>      return cmp(self.__key(), that.__key())
>
>    def __hash__(self):
>      return hash(self.__key())

The main way this breaks down is when comparing objects of different
types. While most comparisons typically are defined in terms of
comparisons on simpler or contained objects, two objects of different
types that happen to have the same "key" shouldn't necessarily be
considered equal.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list