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

Georg Brandl g.brandl at gmx.net
Wed Aug 8 22:29:15 CEST 2012


On 08.08.2012 19:53, Rob Cliffe wrote:
>
> On 08/08/2012 17:59, Oleg Broytman wrote:
>> On Thu, Aug 09, 2012 at 02:18:53AM +1000, Ben Finney <ben+python at benfinney.id.au> wrote:
>>> What is a compelling use case for checking precisely for True or False?
>>     To distinguish False and None for a tri-state variable that can have
>> 3 values - "yes", "no" and "unspecified" - True, False and None in
>> Python-speak.
>>
>> Oleg.
> Other cases:
>       1) I have written a function that returns True, False or a string
> error message.  (No doubt an Exception-subclass object might be better
> style.)

Using the (only) return value for either a result or an error indication
is ugly and error-prone.  It is what makes many APIs painful in languages
that don't have the comfort of e.g. returning a tuple (result, error or None).
Not to mention that there's nothing wrong with raising exceptions.

> So sometimes I really want to test if the result "is True".
>       2) Say you are writing a function to process an arbitrary object,
> e.g. a custom version of repr.  You might well choose to write
>           if obj is True:
>               # processing
>          elif obj is False:
>              # processing
>          elif type(obj) is int:
>               # processing
>         # etc. etc.
> I am sure the examples could be multiplied.
> I can see no reason why we should be discouraged from writing
>       if x is True:
> if that is really what we mean (and need) and not just a verbose way of
> spelling "if x:".

Yeah, just that in most cases that is not really what "we" mean.  And if it
is, why do you feel discouraged anyway?

> Also I find the advice that
>       if x is True:
> is worse than
>       if x==True:
> baffling.  I have been taught that the former executes faster, and
> indeed when I test it I find it is (significantly faster).
> What is the rationale?

Because in most cases you want to accept 1 and 0 too for True and False.

For None, "==" and "is" are equivalent, because no other object is equal
to None.  For True and False, this is different, and using "is" here is
a very stealthy bug.

cheers,
Georg




More information about the Python-ideas mailing list