[Python-ideas] Changing the meaning of bool.__invert__

Nathaniel Smith njs at pobox.com
Fri Apr 8 21:25:41 EDT 2016


On Fri, Apr 8, 2016 at 4:08 PM, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> On Fri, Apr 8, 2016 at 1:34 AM, Nathaniel Smith <njs at pobox.com> wrote:
>> The reason I'm uncertain is that in numpy code, using operations like
>> ~ on booleans is *very* common, because the whole idea of numpy is
>> that it gives you a way to write code that works the same on either a
>> single value or on an array of values, and when you're working with
>> booleans then this means you have to use '~': '~' works on arrays and
>> 'not' doesn't.
>
> Would it be a different story if the logical operators (and, or, not)
> had a protocol, e.g. __not__?  My guess is that ~ was made to work in
> the absence of __not__.

It would, but you can't have a regular protocol for and/or because
they're actually not operators, they're control-flow syntax:

In [1]: a = True

In [2]: a or b
Out[2]: True

In [3]: a and b
NameError: name 'b' is not defined

You could define a protocol for __or__/__ror__/__and__/__rand__
despite this, but it would have weird issues, like 'True and
array([True, False])' would call ndarray.__rand__ and return
array([True, False]), but 'True or array([True, False])' would return
True (because it short-circuits and returns before it can even check
for the presence of ndarray.__ror__). Given this, it's not clear
whether it even makes sense to try.

There was a discussion about this on python-ideas a few months ago,
and Guido asked whether it would still be useful despite these weird
issues, but I dropped the ball and my email to numpy-discussion
soliciting feedback on that is still sitting in my drafts folder...

And I guess you could have a protocol just for 'not', but there might
be some performance concerns (e.g. right now the peephole optimizer
actually knows how to optimize 'if not' into a single opcode), and
overriding 'not' without overriding 'and' + 'or' is probably more
confusing than useful.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-ideas mailing list