Operator Precedence/Boolean Logic

Steven D'Aprano steve at pearwood.info
Thu Jun 23 12:43:01 EDT 2016


On Thu, 23 Jun 2016 11:26 pm, Random832 wrote:

> On Thu, Jun 23, 2016, at 08:37, Steven D'Aprano wrote:
>> You keep saying that, but I've never seen it happen. I've seen cases
>> where people have been surprised by the unexpected truthiness of an
>> object ("I expected an exhausted iterator to be false, but it was
>> true"), but that's not what you seem to be describing.
> 
> I suspect that he's referring to cases like
> http://bugs.python.org/issue4945 where a set of flags that are expected
> to be bool under normal circumstances are interchangeably tested with
> ==, is, boolean checks, and the inversion of any of those.
> 
> If you test with "== True", then you treat 2 as non-truthy. If you test
> with "is True", then you treat 1 as non-truthy. And the reverse of
> either may treat 0 as truthy. If you mix and match any truth-test (e.g.
> "== True") with anything that is not its opposite ("!= True", not e.g.
> "== False") you may end up with situations where neither branch was
> taken and your result is an unexpected state.

Yeah, we can write crap code in Python if you try :-)

> I don't actually agree with him that the object being passed in can be
> blamed for this class of error.

Nor do I. I think that's a clear case where the solution is to stop writing
awful code.

We've all gone through a period were the nicest thing one might say about
our coding is "you don't really understand what you are doing". Some of my
earliest code was nearly as bad. 


> It also occurs to me you could conceivably run into problems if you use
> a passed-in mutable object as a flag to be tested multiple times.

Indeed, but I expect that's more of a theoretical risk than a practical
risk. And, who knows, somebody might find a use for it, to win a bet, for a
code golf competition, or just because they like writing "clever" code:

flag = []
if condition:
    flag.append(None)
else:
    flag.pop()

Could be useful. But beware of overly clever code.


>> The bottom line is, bools offer only a single major API[1]: are they
>> truthy, or falsey? What else can do you with them? Nothing. They
>> support conditional branches, and boolean operators "or" and "and".
>> That's all. They don't have methods to call, or attributes to set. You
>> can use a bool to take the if branch, or the else branch, and that's
>> effectively all.
> 
> Don't forget, they're integers valued 0 and 1. So you can multiply it by
> a number to get 0 or that number. I recently did so (in a code golf
> challenge, not serious code). You can sum an iterable of them to get a
> count of true items.

I would never forget they're also ints. I think I even mentioned that in the
footnote.




-- 
Steven




More information about the Python-list mailing list