Let’s say we want to write a function that takes two arguments and runs a specific code block inside its body only if neither of the arguments is None.
We know that None has a falsy truth value. So at first glance, the following conditional might seem like a valid solution:
|
1 2 3 4 5 |
def bad(x, y): if x and y: # do something |
However, this is not correct—because None isn’t the only value in Python that evaluates to False. Other falsy values include 0, empty strings, empty lists, empty dictionaries, and more. If x or y is 0 or an empty list, the above check would incorrectly skip the code block, even though those values are not None.
Keep in mind: We don’t want to test for truthiness.
What we want is to check whether the values are specifically None.
Correct Approaches
There are correct ways to perform this check. For example:
|
1 2 3 4 5 |
def correct1(x, y): if x is not None and y is not None: # do something |
Or alternatively:
|
1 2 3 4 5 |
def correct2(x, y): if None not in (x, y): # do something |
Both variants ensure you’re only filtering out actual None values—not all falsy ones.
The e-book Python Knowledge Building Step by Step explores this topic further in the chapters “Everyone Has Their Own Truth” – on truth values in Python and “What Is Equal Is Not Necessarily Identical” – on identity vs equality.