[Python-ideas] Revisiting dedicated overloadable boolean operators

Todd toddrjen at gmail.com
Sat Aug 4 00:13:33 EDT 2018


On Fri, Aug 3, 2018 at 5:38 PM, Chris Barker <chris.barker at noaa.gov> wrote:

> On Fri, Aug 3, 2018 at 1:02 PM, Nicholas Chammas <
> nicholas.chammas at gmail.com> wrote:
>
>>  The project overloaded the bitwise operators &, |, and ~ since they
>> could not
>>
> override the boolean operators and, or, and not.
>>
>> I actually think that is a good solution to this problem -- the fact is
> that for most data types bitwise operators are useless -- and for even more
> not-very-useful.
>
> numpy did not do this, because, as it happens, bitwise operators can be
> useful for numpy arrays of integers (though as I write this, bitwise
> operations really aren't that common -- maybe requiring a function call for
> them would be a good way to go -- too late now).
>
> Also, in a common use-case, bitwise-and behaves the same as logical_and,
> e.g.
>
> if (arr > x) & (arr2 == y)
>
> This "works" because both arrays being bitwise-anded are boolean arrays.
>
> So you really don't need to call:
>
> np.logical_and and friends very often.
>
> so -1 on yet another set of operartors.
>
> -CHB
>
>
There are a few problems with using the bitwise operators.

First, and most important in my opinion, is that the precedence is
significantly off from that of the logical operators.  As your own example
shows, any non-trivial example requires a lot of parentheses to keep things
working.  And if you are switching back and forth between, say, array
logical operations and "normal" logical operations it is easy to mess up.

Second is that it can be restricted to only working on boolean-like data
types.  Combining how easy it is to get the precedence wrong with the fact
that getting it wrong can silently fail is not a good combination in my
opinion.  Making sure the operator is actually doing what people want and
expect it to do seems like a big benefit to me.

Third is that it allows both boolean and bitwise operations to be carried
out on the same data types.  Numpy is a special case where the two
basically are equivalent if you are working with boolean arrays.  But that
is a special case.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180804/5d635a87/attachment.html>


More information about the Python-ideas mailing list