why is self not passed to id()?

Terry Reedy tjreedy at udel.edu
Thu Sep 4 17:35:18 EDT 2008



Maric Michaud wrote:
> Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez écrit :

>> class foo(list):
>>     __hash__ = lambda x: id(x)
>>
> 
> Wow ! You are really going on trouble with this, believe me there is a real 
> good reason for list not to be hashable. A dictionnary or set containing some 
> of your foo is virtually inconsistent, read carefully the manual about 
> prerequesites for dict keys, they *need* to be immutable.

No, the id comparison needs to be immutable -- which it is by default 
for object()s, being based on id.  Mutable instances of classes derived 
from object work fine as keys as long as they keep default __eq__ and 
__hash__.  List over-rides the default, so foo needs to reverse that 
override:
   def __eq__(self, other):
     return id(self) == id(other)

This means, of course, that foo loses value-based equality comparison.




More information about the Python-list mailing list