Comparing variables to None is a common operation in Python. However, you may have noticed a discrepancy in the syntax used, leading to the question of whether to use "is" or ==.
In general, it is recommended to use "is" when comparing variables to None. The reason for this is that "is" checks for object identity, while == checks for object equality. In Python, there is only one None object, so comparing anything to None using "is" will always return True if they are the same object.
On the other hand, == checks for object equality. This means that it will return True if the two objects are equal, even if they are not the same object. For example, consider the following code:
class Negator(object): def __eq__(self, other): return not other thing = Negator() print(thing == None) # True print(thing is None) # False
In this example, the Negator class defines an eq method that returns True when the objects are not equal. When comparing thing to None using ==, the custom eq method is called, resulting in True. However, when comparing using is, we see that they are not the same object, resulting in False.
Therefore, if you are strictly checking whether an object is identical to None (i.e., checking for nullity), it is recommended to use "is". If, however, you are checking for equality (i.e., checking if two objects have the same value), you should use ==.
The above is the detailed content of Python None Comparison: 'is' or ==?. For more information, please follow other related articles on the PHP Chinese website!