1

I have tried reading the docs but couldn't get a clear answer.

Is

id(a) == id(b)

the same as

a is b

Likewise is

import unittest
unittest.TestCase.assertNotEqual(id(a), id(b))

therefore the same as

import unittest
unittest.TestCase.assertIsNot(a, b)
david_adler
  • 9,690
  • 6
  • 57
  • 97
  • 1
    @Makoto Little mention of `id` in that question or its answers... (I'd say none, but two answers *mention* it without addressing this question) That question is the olde "`is` seems to work for strings", this question is the more novel "is `is` equivalent to `id()` comparison". –  Mar 17 '13 at 17:03
  • @delnan: The answer contains the fact that `is` tests for identity, and the `id()` function [returns the identity of an object](http://docs.python.org/2/library/functions.html#id0). I'd say there's sufficient mention in the answer. – Makoto Mar 17 '13 at 17:09
  • 2
    @Makoto Putting these two together is question and answer IMHO. –  Mar 17 '13 at 17:10

1 Answers1

1

Yes

"id" in CPython gives you the memory address of the object referred to. The address uniquely identifies an object in the same python process.

Therefore, the meaning of

id(a) == id(b)

is "Are the memory addresses of instance a and b the same?" which is equivalent to "Do a and b refer to the same object?":

a is b

From "id"'s docstring:

id(object) -> integer

Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)

Bernhard Kausler
  • 5,119
  • 3
  • 32
  • 36
  • How about non-CPython implementations such as PyPy? –  Mar 17 '13 at 17:08
  • @delnan: at least in PyPy, `id(a) == id(b) <-> a is b` [(ref)](http://pypy.readthedocs.org/en/latest/cpython_differences.html#object-identity-of-primitive-values-is-and-id). – DSM Mar 17 '13 at 17:15
  • @delnan If id(a)==id(b) is true in CPython then it is true in PyPy. This is not always the case the other way around. Try: (1000000000 + 1) is (1000000000+1). The latter is always true in PyPy, but not in CPython. – Bernhard Kausler Mar 17 '13 at 17:26
  • 1
    Great. I didn't ask because I don't know that (I even know *why* it's like that), I asked because the *answer* could use this information. –  Mar 17 '13 at 17:28
  • According to the Python Language Reference at the end of section 5.9. Comparisons the 'is' operator tests for object identity. So assertIsNot(a,b) can always be replaced with assertNotEqual(id(a), id(b)). Depending on implementation internals you could get different results when it comes to value types, so avoid using 'is' when you want to compare values, as you don't know if it will work on othe implementations or event future implementations. – TAS Mar 17 '13 at 17:33