Boolean comparison & PEP8
Terry Reedy
tjreedy at udel.edu
Sun Jul 28 22:36:42 EDT 2019
On 7/28/2019 7:55 AM, Jonathan Moules wrote:
> Lets say I want to know if the value of `x` is bool(True).
> My preferred way to do it is:
>
> if x is True:
> pass
If you know that expression x is boolean, and one usually knows or
should know whether is it or is not, '= True' and 'is True' and
similarly for False are redundant. Why not 'if x is True is True' and
so on.
> Because this tests both the value and the type.
See below.
Newbies *have* written things like 'if (x == 3) is True' and this is
what prompted this entry in PEP 8.
> """
> Don't compare boolean values to True or False using ==.
>
> Yes: if greeting:
> No: if greeting == True:
> Worse: if greeting is True:
> """
> If `x` can also have a value of "1"(str) or 1(int)
Have you run across any stdlib function that returns such a mixture of
types? Remember that PEP 8 is specifically a style guide for stdlib code.
--
Terry Jan Reedy
More information about the Python-list
mailing list