It is possible to do comparisons against
None using equality (
if foo == None: # do something if bar !== None: # do something
if foo is None: # do something if bar is not None: # do something
This is also supported by PEP, which states:
"Comparisons to singletons like
Noneshould always be done with
is not, never the equality operators."
The reason for this is because:
is not) actually checks for an object's identity (i.e. whether two objects are indeed the same object);
- Equality (
!=) is applied by calling the
__ne__()) method of an object, which can be overridden. This means that how two objects are considered "equal" can differ from object to object.
class Foo(): def __eq__(self, obj): return obj is None foo = Foo() print(foo == None) # True print(foo is None) # False
In the example above, you can see that
None are actually not the same objects, and thus, correctly fail the identity check with the
is operator. Comparatively, this is different when checking for equivalence (as shown in the example above), which can have a different meaning depending on the definition (if any) in the object class.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.