is operator versus id() function

Candide Dandide c.candide at laposte.net
Fri Apr 5 09:49:14 EDT 2013


Until now, I was quite sure that the is operator acts the same as the id builtin function, or, to be more formal, that o1 is o2 to be exactly equivalent to id(o1) == id(o2). This equivalence is reported in many books, for instance Martelli's Python in a Nutshell.

But with the following code, I'm not still sure the equivalence above is correct. Here's the code :


#--------------------------------------------------------
class A(object):
    def f(self):
        print "A"

a=A()
print id(A.f) == id(a.f), A.f is a.f
#--------------------------------------------------------


outputing:

True False

So, could someone please explain what exactly the is operator returns ? The official doc says :

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



More information about the Python-list mailing list