[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

keying by identity in dict and set

On Sun, Oct 20, 2019 at 3:08 AM Steve White <stevan.white at> wrote:
> It would appear that if __hash__ returns the id, then that id is used
> internally as the key, and since the id is by definition unique, no
> key collision ever occurs -- at least in every Python implementation
> I've tried. It also seems that, for a class instance obj,
>     hash( hash( obj ) ) == hash( obj )
>     hash( id( obj ) ) == id( obj )
> These are very strong and useful properties.  Where are they documented?

There are two rules that come into play here. One is that smallish
integers use their own value as their hash (so hash(1)==1 etc); the
other is that dictionaries actually look for something that matches on
identity OR equality. That's why using identity instead of equality
will appear to work, even though it can cause other problems when you
mismatch them.