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()

      

+3


source to share


6 answers


will return True if two variables point to the same object == if the objects referenced by the variables are equal.



>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

      

+5


source


==

tests for equality. Two non-identical objects can be equal.



is

checks for identity, that is, both refer to the same object.

+7


source


if money_in_wallet is money_that_was_in_wallet(two_weeks_ago):
    print("I still live with my parents and have no income or expenses")
elif money_in_wallet == money_that_was_in_wallet(two_weeks_ago):
    print("Good, my budget is exactly balanced")

      

+2


source


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

0


source


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.

0


source


are tests if both inputs are actually the same object. This is the same address in memory.

== calls the __ eq __ method on one of the input objects. The objects can then define their own __ eq __ method and decide what is equal and what is not.

0


source







All Articles