EXPLANATION
You must realize that True
, False
, and None
are all singletons in Python, which means that there exist and can only exist one, single instance of a singleton object, hence the name singleton. Also, you can't modify a singleton object because its state is set in stone, if I may use that phrase.
Now, let me explain how those Python singletons are meant to be used.
Let's have a Python object named foo
that has a value None
, then if foo is not None
is saying that foo
has a value other than None
. This works the same as saying if foo
, which is basically if foo == True
.
So, not None
and True
work the same way, as well as None
and False
.
>>> foo = not None
>>> bool(foo)
True
>>> foo = 5 # Giving an arbitrary value here
>>> bool(foo)
True
>>> foo = None
>>> bool(foo)
False
>>> foo = 5 # Giving an arbitrary value here
>>> bool(foo)
True
The critical thing to realize and be aware of when coding is that when comparing two objects, None
needs is
, but True
and False
need ==
. Avoid using if foo == None
, only use if foo is None
. Also, avoid using if foo != None
and only use if foo is not None
.
WARNING
If you are using if foo
or if not foo
when the value of foo
happens to be None
, beware of potential bugs in your code. So, don't check for a potential None
value in conditional statements this way. Be on the safe side by checking for it as explained above, i.e., if foo is None
or if foo is not None
. It is very important to follow best practices shared by Python experts.
REMINDER
True
is a 1
and False
is a 0
.
In the old days of Python, we only had the integer 1
to represent a truthy value and we had the integer 0
to represent a falsy value. However, it is more understandable and human-friendly to say True
instead of 1
and it is more understandable and human-friendly to say False
instead of 0
.
GOOD TO KNOW
The bool
type (i.e., values True
and False
) are a subtype of the int
type. So, if you use type hints and you annotate that a function/method returns either an int
or a bool
(i.e., -> int | bool
or -> Union[int, bool]
), then mypy (or any other static type checker) won't be able to correctly determine the return type of such a function/method. That's something you need to be aware of. There's no fix for this.