keying by identity in dict and set

Random832 random832 at fastmail.com
Sat Nov 2 01:10:54 EDT 2019


On Sun, Oct 27, 2019, at 03:24, Steve White wrote:
> Yes, there are several options, but they all involve an extra layer
> that detracts between the interface I am building and my user's code.
> In this situation, the objects being used as keys are conceptually the
> unique entities that the user deals with, even if their data is
> non-unique.  And I do not want to subject the user to the un-pythonic
> use of some operator other than '==' to determine their equivalence.

I'm honestly a little bit confused as to what the type of the objects you are using which it's reasonable to do this with but doesn't already work that way

> As near as I can tell, returning the id() in __hash__() results in a
> perfect hash key.  I really want to know if that is true.
> Because if it is true, any further layer is simply covering for a
> failing in the documentation.

And if you can override __hash__ you can, obviously, also override __eq__ to do whatever you want. You can return id in both. In fact, that is the default behavior of objects, assuming your type is not inherited from another type that does something different. Regardless, __hash__ and __eq__ should be consistent with each other.


More information about the Python-list mailing list