object identity and hashing

castironpi at gmail.com castironpi at gmail.com
Sun Feb 24 23:02:55 EST 2008


On Feb 24, 9:28 pm, George Sakkis <george.sak... at gmail.com> wrote:
> On Feb 24, 9:11 pm, castiro... at gmail.com wrote:
>
>
>
>
>
> > On Feb 24, 7:58 pm, Jeff Schwab <j... at schwabcenter.com> wrote:
>
> > > castiro... at gmail.com wrote:
> > > > Can someone explain this?
>
> > > >>>> a= {}
>
> > > Create an empty dict and bind it to the name a.
>
> > > >>>> a[(3,)]= 0
>
> > > Set the key/value pair (3,):0 to the dict.
>
> > > >>>> (3,) in a
>
> > > Is (3,) one of the keys in the dict?
>
> > > > True
>
> > > Yes, it is.
>
> > > >>>> (3,) is (3,)
>
> > > Create two separate tuples (that happen to be equivalent).  Are they the
> > > same object?
>
> > > > False
>
> > > No, they are not.
>
> > > Every time you write (3,), you are potentially creating a new object.
> > > These objects have equal values (and hash codes), so they are
> > > interchangeable for purposes of keying a dict.
>
> > I see.  You stated,
>
> > > Is (3,) one of the keys in the dict?
>
> > > > True
>
> > > Yes, it is.
>
> > It isn't, but it does equal a key that's already in the dict.
>
> Right, dict lookup depends on object hashing (__hash__) and equality
> (__eq__), not identity. There are legitimate cases where lookup should
> be based on identity [1], but they are far less common than those
> based on equality.
>
> George
>
> [1]http://www.martinfowler.com/eaaCatalog/identityMap.html- Hide quoted text -
>
> - Show quoted text -

[1] illustrates a case in which 'a is a' returns False, and in the
other corner of the DeMorgan table, there is 'a is b' returns True for
'a == b' False.



More information about the Python-list mailing list