(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. This scheme would eliminate the tedium of keeping the __hash__ method in sync with the __cmp__/__eq__ method, and writing a __key__ method would involve writing less code than a naive __eq__ method, since each attribute name only needs to be mentioned once instead of appearing on either side of a "==" expression. On the other hand, this idea doesn't work in all situations (for instance, I don't think you could define the default __cmp__/__hash__ semantics in terms of __key__), it would only eliminate two one-line methods for each class, and it would further complicate the "==" operator (__key__, falling back to __eq__, falling back to __cmp__, falling back to object identity--ouch!) If anyone thinks this is a good idea I'll investiate how many places in the standard library this pattern would apply. --jw _______________________________________________ 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