Here's one from my own code, where I allow a query to be specified through --query , or as a hex-encoded query through --hex-query or as an input file through --queries, but I only allow one of them:
if bool(args.query) + bool(args.hex_query) + bool(args.queries) > 1:
>Here's one from my own code, where I allow a query to be specified through --query , or as a hex-encoded query through --hex-query or as an input file through --queries, but I only allow one of them
"Better" only if you want the default error message. As the second rated answer for the question comments: "If you like to have more control about error message and the like, you can of course check the results later"
Looks like the libraries use the technique to handle those conditional off-by-one situations that other languages might resolve with a ternary expression. Thanks!
FWIW, I only searched for lines containing 'bool(' and '+'. That means I missed some of the other uses, like:
unittest2/compatibility.py:25:
if bool(unc_path) ^ bool(unc_start):
scipy/signal/fir_filter_design.py:266:
pass_nyquist = bool(cutoff.size & 1) ^ pass_zero
pypysrc/py/_path/common.py:65:
if bool(value) ^ bool(meth()) ^ invert:
There's also a place where the bool is turned into an int, but that extra conversion isn't actually needed - the following would work without the int() call:
True == 1, False == 0, so this counts how many items in iterable are greater than 3.
But I think that's the only non-dirty way I've used it, and if that wasn't possible a trivial count() function could do the job.
If I remember correctly, bool subclasses int mostly for compatibility with pre-existing conventions. People were already defining their own "True = 1" and "False = 0" constants before they became part of the language.
That works better if you expect things in iterable that aren't ints, but it's still summing bools. int(x) > 3 returns a bool, so in the end it's still doing something similar to
sum([True, False, False, True, True, False])
But if bools didn't implicitly behaves like ints, but could still be converted to ints, you could do this:
Can you provide a concrete example for when this would be useful? I assume you're not talking about binary arithmetic.