id(a) == id(b) and a is not b --> bug?

Terry Reedy tjreedy at udel.edu
Fri Jun 6 02:41:03 CEST 2003


"Erik Max Francis" <max at alcyone.com> wrote in message
news:3EDFDDBC.673E0F25 at alcyone.com...
> Gerrit Holl wrote:
>
> > The `is' operator compares the identity of two objects; the id()
> > function returns an integer representing its identity
> >
> > This would mean that "id(a) == id(b)" is the same as "a is b".
> ...
> > $ python meta.py
> > id's equal => True
> > same object => False
> >
> > Is this a bug? It is true both for Python 2.3b1+ and Python 2.2.
>
> Weird as it seems, it happens in some cases where objects are
> dynamically generated by the code you write, whether it looks like
> you're dynamically generating objects or not.  You can see similar
> things with plain old methods:
>
> >>> class C:
> ...  def m(self): pass
> ...
> >>> c = C()
> >>> c.m is c.m
> 0
> >>> id(c.m) == id(c.m)
> 1

Even simpler example with plain old builtins (with same explanation):
>>> id([]) == id([])
1
>>> [] is []
0

> It's happening because accessing a method dynamically creates an
unique
> object and goes away when you're finished with it.  So when an
> expression needs both at the same time (c.m is c.m), two unique
objects
> are created, but when an expression doesn't need both at the same
time
> (id(c.m) == id(c.m)), an object gets created with an ID, is
destroyed,
> and then a second object is created with the same ID (since the last
one
> just got reclaimed) and their IDs compare equal.  Weird, huh?  (It
> surprised me when I first saw it, too.)

I was fooled too until I realised that ids 'unique' is only guaranteed
at any moment of time.

Terry J. Reedy






More information about the Python-list mailing list