Search code examples
pythonoperators

Python != operation vs "is not"


In a comment on this question, I saw a statement that recommended using

result is not None

vs

result != None

What is the difference? And why might one be recommended over the other?


Solution

  • == is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

    is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

    You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.