user6067622
user6067622

Reputation:

`is` comparison: direct object comparison vs. comparison of object identity representation

So I am getting the following results:

  1. () is () returns True (comparison between two objects)
  2. id(()) is id(()) returns False. (comparison between the representations of object identities)

According to the python documentation:

The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity.

Given case (1), object () has the same identity (memory address) as object (); but in case (2), the representations of their identities are not identical to each other.

Why is that?

Upvotes: 2

Views: 237

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

The id(..) function returns an integer that represents the "identity" of an object so to speak. Although it is true that if two variables x and y refer to the same object, x is y succeed, and the result of id(x) is equal to id(y), that does not mean those integers themeselves are the same object.

You thus should use:

id(()) == id(())
#      ^ == not is

In Python, even ints are objects, and although usually there is a cache such that small integers indeed refer to the same object, the following test will usually fail:

>>> 1234567890 is (1234567891-1)
False
>>> 1234567890 == (1234567891-1)
True

Upvotes: 1

Related Questions