I have a boolean flag that can be None
, True
, or False
. Each value has a different meaning.
I understand the Pythonic way of checking for True
and None
and not None
are:
if bool_flag:
print("This will print if bool_flag is True")
# PEP8 approved method to check for True
if not bool_flag:
print("This will print if bool_flag is False or None")
# Also will print if bool_flag is an empty dict, sequence, or numeric 0
if bool_flag is None:
print("This will print if bool_flag is None")
if bool_flag is not None:
print("This will print if bool_flag is True or False")
# Also will print if bool_flag is initialized as anything except None
And if you need to check for all three in an if statement block, you would use a laddered approach, for example:
if bool_flag:
print("This will print if bool_flag is True")
elif bool_flag is None:
print("This will print if bool_flag is None")
else:
print("This will print if bool_flag is False")
# Note this will also print in any case where flag_bool is neither True nor None
But what is the Pythonic way of just checking for a value of False
when the flag can also be None
or True
as valid values? I have seen several questions but there doesn’t seem to be a consensus.
Is it “more pythonic” to write:
# Option A:
if isinstance(bool_flag, bool) and not bool_flag:
print("This will print if bool_flag is False")
# Option B:
if bool_flag is not None and not bool_flag:
print("This will print if bool_flag is False")
## These two appear to be strictly prohibited by PEP8:
# Option C:
if bool_flag is False:
print("This will print if bool_flag is False")
# Option D:
if bool_flag == False:
print("This will print if bool_flag is False")
This topic has been discussed before:
- What is the correct way to check for False?
- In Python how should I test if a variable is None, True or False
- Is there a difference between “== False” and “is not” when checking for an empty string?
- Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result?
- Is there a difference between “==” and “is”?
This appears to be the closest answer to my question out of what is available (providing Option A above), but even this Answer is ambiguous (suggesting Option C as well):
- /a/37104262/22396214
However, this answer points out that if not flag_bool
is equivalent to if bool(flag_value) == False
which would imply that checking for False
equivalence using the ==
operator is the official Pythonic method of checking for False (Option D):
- /a/36936790/22396214
But that directly contradicts this answer that ‘== False’ (Option D) should never be used:
- /a/2021257/22396214