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

Erik Max Francis max at alcyone.com
Thu Jun 5 20:18:04 EDT 2003


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

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.)

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ You can't expect to win unless you know why you lose.
\__/  Benjamin Lipson




More information about the Python-list mailing list