if obj == None, use if obj is NoneIn Python, when you write:
obj == None
you're not directly checking if
obj is the value None. Instead, you're asking if the object is equal to None.Yes, in many cases, the result will be the same as for the code:
obj is None
But the behavior of these two variants is different, and this difference is important.
When you use:
obj == None
Python calls the
__eq__ method on the object. That is, the object itself decides what it means to be "equal to None". And this method can be overridden.If
obj is an instance of a class in which __eq__ is implemented so that when compared with None, it returns True (even if the object is not actually None), then obj == None may mistakenly give True.Example:
class Weird:
def __eq__(self, other):
return True # Always asserts that it's equal
obj = Weird()
print(obj == None) # True
print(obj is None) # False
Here, it can be seen that
obj == None returns True due to the custom behaeqf the __eq__ operator in the class.Therefore, when using
obj == None, the result is not always predictable.On the other hand, when you write:
obj is None
you're using the
is operator, which cannot be overridden. This means that the result will always be the same and predictable.The
is operator checks the identity of objects, that is, whether two references point to the same object. Since None is a singleton (the only instance), obj is None is the correct and most efficient way to perform such a check.❤️ Therefore, it is always recommended, and this is best practice, to use
obj is None instead of obj == None for predictability and efficiency.👉 https://t.me/DataScienceQ
