object identity and equivalence

Sandy Norton sandskyfly at hotmail.com
Mon Nov 19 12:54:29 EST 2001


I apologize if this is a stupid question that has been asked before.
(I feel kinda stupid asking it :-) but I've searched the FAQ to no
avail and google is not really responsive to the keywords in question.
But this question is pestering me...

I am a bit confused about when it is correct to use object identity
"is" for comparisons and when I should use the equals '==' operator.

I always seem to get the same results with both:

>>> class Person: pass
... 
>>> p1 = Person()
>>> p2 = Person()
>>> p1 is p1
1
>>> p1 == p1
1
>>> p1 is p2
0
>>> p1 == p2
0
>>> 1.0 is 1.0
1
>>> 1.0 == 1.0
1
>>> 1 is 2
0
>>> 1 == 2
0
>>> (2+3) is 5
1
>>> (2+3) == 5
1

I haven't personally come across cases where these two operators don't
produce the same results with the same operands. Of course I am not
assuming the semantic equivalence of the operators, as it makes sense
that comparing object identity is the not the same as comparing object
value. But could someone offer me an example that uses the same two
operands with 'is' and '==' and produces 'different' results.

Aside: I'm assuming you can overload the '==' operator but not the
'is' operator? Is this true?

There! I've announced my ignorance to the world. Feel better already!

Sandy



More information about the Python-list mailing list