tags:

views:

163

answers:

3

How does is operator determine if two objects are the same? How does it work? I can't find it documented.

+5  A: 

From the documentation:

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address).

This would seem to indicate that it compares the memory addresses of the arguments, though the fact that it says "you may think of it as the object's address in memory" might indicate that the particular implementation is not guranteed; only the semantics are.

danben
In particular, I would assume that small integers (which have the same id) may not actually be stored anywhere specific in memory.
Andrew Jaffe
CPython compares the memory addresses, however that is an implementation detail like the value returned by id(). When i'm already mentioning id() it should be said that calls to id() on implementations with a moving GC can be very expensive, so one should avoid calling it.
DasIch
+3  A: 

Comparison Operators

Is works by comparing the object referenced to see if the operands point to the same object.

>>> a = [1, 2]
>>> b = a
>>> a is b
True
>>> c = [1, 2]
>>> a is c
False

c is not the same list as a therefore the is relation is false.

msw
But! Be aware that this *can* be different for certain immutable objects. For example, a = 5; b = 5; a is b returns True, at this moment, on this laptop, on this version of Python. You can't guarantee that two objects will be different just because they were initialized separately.
Just Some Guy
Indeed, the almost sole application of `is` in Python is for comparing singletons, like `if foo is None` or `sentinel = object() ... if bar is sentinel`.
Mike Graham
@Just: You *can* guarantee that some objects are different when separately initialized, as this answer has with lists, because you *must* know if `a.append(v)` will modify *c*.
Roger Pate
@Roger: What I meant was that you don't always know that Python will yield two distinct objects just because they were initialized separately. That alone is not enough to guarantee distinction. I wanted to give a counterexample to msw's example, where they *were* different, showing that it's not always the case. Yes, you must use *is* to to verify distinctness if that's important to you, which was kind of my point. :-)
Just Some Guy
A: 

To add to the other answers, you can think of a is b working as if it was is_(a, b):

def is_(a, b):
  return id(a) == id(b)

Note that you cannot directly replace a is b with id(a) == id(b), but the above function avoids that through parameters.

Roger Pate
Thanks for the update!
bodacydo