Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between keyword: is and == in python

the python keyword is is supposed to be used in place of the == operator according to python style guides.

However they don't always do exactly the same thing as shown here. Why? What is the actual difference, and what is the proper usage?

import unittest

class testIS(unittest.TestCase):
    def test_is(self):
        self.assertEqual(1,1)

if __name__ == '__main__':
    unittest.main()

Which works... but the following does not...

import unittest

class testIS(unittest.TestCase):
    def test_is(self):
        self.assertEqual(1,1)

if __name__ is '__main__':
    unittest.main()
like image 537
jonathanbsyd Avatar asked Apr 27 '26 10:04

jonathanbsyd


1 Answers

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

is tests for identity, i.e. whether both refer to the same one object.

like image 133
hamstergene Avatar answered Apr 29 '26 01:04

hamstergene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!