Curiously:
>>> a = 123 >>> b = 123 >>> a is b True >>> a = 123. >>> b = 123. >>> a is b False
Seems a is b
being more or less defined as id(a) == id(b)
. It is easy to make bugs this way:
basename, ext = os.path.splitext(fname) if ext is '.mp3': # do something else: # do something else
Some fnames unexpectedly ended up in the else block. The fix is simple, we should use ext == '.mp3'
instead, but nonetheless if ext is '.mp3'
on the surface seems like a nice pythonic way to write this and it's more readable than the "correct" way.
Since strings are immutable, what are the technical details of why it's wrong? When is an identity check better, and when is an equality check better?
There's a subtle difference between the Python identity operator ( is ) and the equality operator ( == ). Your code can run fine when you use the Python is operator to compare numbers, until it suddenly doesn't.
'is' and '==' operators in Python. The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.
The 'is' is known as the identity operator. The == operator helps us compare the equality of objects. The is operator helps us check whether different variables point towards a similar object in the memory. We use the == operator in Python when the values of both the operands are very much equal.
== is always for testing equality. in most cases used as a drop-in replacement for <- , the assignment operator. used as the separator for key-value pairs used to assign values to arguments in function calls.
They are fundamentally different.
==
compares by calling the __eq__
methodis
returns true if and only if the two references are to the same objectSo in comparision with say Java:
is
is the same as ==
for objects==
is the same as equals
for objectsAs far as I can tell, is
checks for object identity equivalence. As there's no compulsory "string interning", two strings that just happen to have the same characters in sequence are, typically, not the same string object.
When you extract a substring from a string (or, really, any subsequence from a sequence), you will end up with two different objects, containing the same value(s).
So, use is
when and only when you are comparing object identities. Use ==
when comparing values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With