[Python-ideas] Programming recommendations (PEP 8) and boolean values

Steven D'Aprano steve at pearwood.info
Wed Aug 8 19:33:23 CEST 2012

On 09/08/12 00:28, Guido van Rossum wrote:
> I'd be strongly against changing that rule. If you don't want other types
> than bool, use an isinstance check. Code using "is True" is most likely a
> bug. (It's different for None, since that has no second value that is
> assumed.)

Furthermore, the problem with testing flags for their truth-value (truthiness)
using "flag is True" is that you never know when to stop, since the comparison
also returns a flag which needs to be checked for its truth-value:

if (flag is True) is True is True is True is ... # and so on ad infinitum

which of course is absurd. If you can trust the truthiness of "flag is True",
you can also trust the truthiness of flag on its own.

If you truly need to check that flag is not only a true-value, but is
specifically the bool True, then "flag is True" might be acceptable, provided
it was clear in context why you were doing that. (But why would you need to?
Presumably that should be a rare occurrence.) An isinstance check makes it
obvious that the type matters.

"type(flag) is bool" makes it even more obvious that you want a bool and
nothing but a bool, not even a subclass. I note, however, that all three of
CPython, IronPython and Jython prohibit you from subclassing bool, but this
seems to be an implementation detail. At least, it isn't documented as a
language requirement here:


Coming back to Paul's request to modify the wording, I think that it is fine
as it stands. We know that PEP 8 allows breaking the rules when necessary.
Not every exception to PEP 8 needs to be explicitly documented, and we
shouldn't dilute the message that "if flag" is the idiomatic Pythonic way to
test a flag by talking about the rare case where it isn't.


More information about the Python-ideas mailing list