Python – Does the `is` Operator Use a __magic__ Method?

operatorspython

The is operator is used test for identity.

I was wondering if the is operator and id() function call any __magic__ method, the way == calls __eq__.

I had some fun checking out __hash__:

class Foo(object):
    def __hash__(self):
        return random.randint(0, 2 ** 32)

a = Foo()
b = {}
for i in range(5000):
    b[a] = i

Think about dict b and the value of b[a]

Every subsequent lookup of d[a] is either a KeyError or a random integer.

But as the docs on the special methods state

[the default implementation of] x.__hash__() returns id(x).

So there is relation between the two, but just the other way around.

I've seen many questions on is and id here, and the answers have helped many confused minds, but I couldn't find an answer to this one.

Best Answer

No, is is a straight pointer comparison, and id just returns the address of the object cast to a long.

From ceval.c:

case PyCmp_IS:
    res = (v == w);
    break;
case PyCmp_IS_NOT:
    res = (v != w);
    break;

v and w here are simply PyObject *.

From bltinmodule.c:

static PyObject *
builtin_id(PyObject *self, PyObject *v)
{
    return PyLong_FromVoidPtr(v);
}

PyDoc_STRVAR(id_doc,
"id(object) -> integer\n\
\n\
Return the identity of an object. This is guaranteed to be unique among\n\
simultaneously existing objects. (Hint: it's the object's memory address.)");