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

Josiah Carlson jcarlson at uci.edu
Mon Nov 7 00:12:36 CET 2005


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())
> 
> I wonder if it wouldn't make sense to formalize this pattern with a 
> magic __key__ method such that a class with a __key__ method would 
> behave as if it had interited the definitions of __cmp__ and __hash__ above.

You probably already realize this, but I thought I would point out the
obvious.  Given a suitably modified MyClass...

>>> x = {}
>>> a = MyClass()
>>> a.a = 8
>>> x[a] = a
>>> a.a = 9
>>> x[a] = a
>>>
>>> x
{<__main__.MyClass instance at 0x007E0A08>: <__main__.MyClass instance at 0x007E
0A08>, <__main__.MyClass instance at 0x007E0A08>: <__main__.MyClass instance at
0x007E0A08>}

Of course everyone is saying "Josiah, people shouldn't be doing that";
but they will.  Given a mechanism to offer hash-by-value, a large number
of users will think that it will work for what they want, regardless of
the fact that in order for it to really work, those attributes must be
read-only by semantics or access mechanisms.  Not everyone who uses
Python understands fully the concepts of mutability and immutability,
and very few will realize that the attributes returned by __key() need
to be immutable aspects of the instance of that class (you can perform
at most one assignment to the attribute during its lifetime, and that
assignment must occur before any hash calls).


Call me a pessimist, but I don't believe that using magical key methods
will be helpful for understanding or using Python.

 - Josiah



More information about the Python-Dev mailing list