object identity and equivalence
erno-news at erno.iki.fi
Mon Nov 19 19:06:34 CET 2001
In article <b03e80d.0111190954.ce015b8 at posting.google.com>,
sandskyfly at hotmail.com (Sandy Norton) writes:
| 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.
as a rule, a is b implies a == b (except for odd things like floating
point NaNs that compare inequal to themselves).
a == b does not imply a is b.
| 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.
for some immutable objects like numbers and strings, python caches
some of those according to a few rules for efficiency reasons, so it
is unpredictable if a is b given two same-valued objects.
mutable objects like user class instances and lists and dictionaries
and such can not be cached.
| 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!
More information about the Python-list