Rob Cliffe email@example.com writes:
On 08/08/2012 17:59, Oleg Broytman wrote:
On Thu, Aug 09, 2012 at 02:18:53AM +1000, Ben Finney firstname.lastname@example.org wrote:
What is a compelling use case for checking precisely for True or False?
By “compelling use case for”, I mean “a use case which is best satisfied by”. So use cases which *could* use this are not compelling if they are better satisfied by some other, existing way.
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.)
You get to the nub of it: there are clearly better ways to meet the use case (for this one, use an exception), so this is not a compelling use case for precise checking of True and False.
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
Again, this is much clearer written as:
if type(obj) is bool: # processing if type(obj) is int: # processing
So not a compelling use case for checking specific values.
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:".
I don't see any of the cases presented so far (other than unit testing, which is already special enough to break most of the rules) as best satisfied by precise checking for specific values of bool.
On the other hand, ‘if foo is True’ is a common beginner mistake that we meet frequently in ‘comp.lang.python’, and is almost always better written as ‘if foo’. It's that kind of advice that belongs in PEP 8.