Operator Precedence/Boolean Logic

Random832 random832 at fastmail.com
Thu Jun 23 09:26:36 EDT 2016


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.

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

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.

> 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.



More information about the Python-list mailing list