[Python-ideas] Programming recommendations (PEP 8) and boolean values
Rob Cliffe
rob.cliffe at btinternet.com
Wed Aug 8 19:53:29 CEST 2012
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.)
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:".
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?
Rob Cliffe
More information about the Python-ideas
mailing list