Python None Comparisons: Should You Use "is" or ==?
In Python, you may encounter a warning when comparing variables to None using ==, while no warning is issued when using is. Both syntaxes are valid, but the use of my_var is None is generally preferred.
Why is "is" Preferred for None Checks?
The key difference between is and == lies in their purpose. == checks for equality, while is checks for object identity. In the case of comparing variables to None, we want to determine if the variable is specifically the None object, not just an object that is equivalent to it.
None is a unique object in Python, meaning there is only one instance of it. When you use my_var is None, you are checking whether my_var and None are the same object. This check is more specific and reliable than using my_var == None.
Equality vs. Identity
To illustrate the difference, consider a custom class Negator:
class Negator(object): def __eq__(self, other): return not other
If you create an instance of Negator and compare it to None, you will get:
thing = Negator() print(thing == None) # True print(thing is None) # False
thing == None returns True because the Negator class overrides the eq method to always return True when compared to any other value except itself. However, thing is None returns False because the two objects are not the same object.
Conclusion
For None checks, it is generally preferred to use my_var is None to ensure that you are specifically checking for the None object. == can be used when you want to check for equality, but keep in mind that this may be unreliable when dealing with custom classes that override comparison methods.
以上がPython なしの比較: 「is」または「==」を使用する必要がありますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。