John Williams <[EMAIL PROTECTED]> 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

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to