What is the difference between keyword: is and == in python
the python keyword is is
supposed to be used instead of an operator ==
according to the python style guides.
However, they don't always do the same as shown here. What for? What is the actual difference and what is the correct usage?
import unittest
class testIS(unittest.TestCase):
def test_is(self):
self.assertEqual(1,1)
if __name__ == '__main__':
unittest.main()
Which works ... but the next doesn't ...
import unittest
class testIS(unittest.TestCase):
def test_is(self):
self.assertEqual(1,1)
if __name__ is '__main__':
unittest.main()
source to share
Departure...
http://docs.python.org/reference/expressions.html#not-in
... What states ...
Operators is
and is not
check the object identifier: x is y true if and only if x and y are the same object
source to share
The Python keyword 'is' tests an object identifier, and the == operator tests for equality. For example:
>>> if Car1 is Car2:
>>> [do something...]
this code checks if Car1 and Car2 belong to the same car and
>>> if Car1 == Car2:
>>> [do something...]
checks if Car1 and Car2 are of the same quality, that is, if they have the same model, color, etc.
For this reason __name__
, it "__main__"
returns False, because the string "__main__"
and the value stored in __name__
are really two different string objects. Therefore, to check that the string value __name__
is equal __main__
, use the == operator.
source to share