In Python, None
is a singleton object (i.e. only one instance of it ever exists).
You can validate that using None
always references to the same object (no matter how many times it's called) by using Python's identity function "id()
", for example, like so:
print(id(None)) # 139898125892800 foo = None print(id(foo)) # 139898125892800 def bar(): pass print(id(bar())) # 139898125892800
The examples above show that the id of None
is the same (no matter how many times it's called), which means that they point to the same object.
Since None
always references to the same object, you can use the is
(or is not
) operators to compare values against it:
if foo is None: # do something if foo is not None: # do something
Although, it is possible to use the equality operator (==
or !==
) to compare against None
, it is not recommended. You should use is
(or is not
) operator instead.
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.