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.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.