What is the difference between "a is b" and "id(a) == id(b)" in Python?

Posted by bp on Stack Overflow See other posts from Stack Overflow or by bp
Published on 2010-05-25T15:39:52Z Indexed on 2010/05/25 15:41 UTC
Read the original article Hit count: 146

Filed under:
|

The id() inbuilt function gives...

an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

The is operator, instead, gives...

object identity

So why is it possible to have two objects that have the same id but return False to an is check? Here is an example:

>>> class Test():
...   def test():
...     pass
>>> a = Test()
>>> b = Test()
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False

A more troubling example: (continuing the above)

>>> b = a
>>> b is a
True
>>> b.test is a.test
False
>>> a.test is a.test
False

© Stack Overflow or respective owner

Related posts about python

Related posts about Identity