Why do you need to explicitly test for True
values? You rarely, if ever do need narrow your test down to a specific type. I'd rethink your use case here; if you are building an API that'll return a bool
instead of in int
for out-of-band conditions, then use exceptions instead.
If you do have to test for True
only, then use
if n is True:
because the boolean values are meant to be singletons like None
. See the Programming recommendations section:
Comparisons to singletons like None
should always be done with is
or is not
, never the equality operators.
Moreover, because issubtype(bool, int)
is true (for historical reasons; bool
was introduced rather late in Python), n == True
is also true for n = 1
, if you can only accept True
here then you can only use is True
. You could also use isinstance(n, bool) and n
, which would allow for subclasses of bool
, but I cannot imagine there ever be a use for such a type, and in current implementations, bool
explicitly prohibits being subclassed.
The PEP 8 rule about using not using if cond is True:
is specifically called out because it limits the value of cond
to the bool
only.
Last but not least, PEP 8 starts with this:
A Foolish Consistency is the Hobgoblin of Little Minds
[...] But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best.
Only follow PEP 8 if it suits your needs.