[Python-ideas] [Python-ideos] Dedicated overloadable boolean operators

Nathaniel Smith njs at pobox.com
Tue Nov 24 03:30:57 EST 2015


On Nov 23, 2015 22:34, "Random832" <random832 at fastmail.com> wrote:
>
> On 2015-11-24, Chris Angelico <rosuav at gmail.com> wrote:
> > I think it's reasonable, except for the potential confusion of having
> > *three* "and" operators. The one with the word is never going to
> > change - its semantics demand that it not be overridable.
>
> How? Are you referring to the short-circuit? C# allows
> overloading the short-circuit operators by doing it in two
> parts - in pseudocode:
>
> a and b: a if a.__false__() else a & b
> a or b: a if a.__true__() else a | b
>
> There's no fundamental reason short-circuiting "demands" that it
> not be overridable, just because C++ can't do it.

No, I disagree -- for us short circuiting makes overriding extremely
difficult, probably impossible, because in python in general and in the use
cases being discussed here in particular, the right-hand side argument
should have a chance to overload. It's going to be brutal on newbies and
general code comprehensibility if

  True and array_of_bools

or

  True and sqlalchemy_expression

act totally differently than the mirrored versions, but this is an
unavoidable if you have both short circuiting and overloading.

(Example of where you'd see code like this:

if restrict_user_id is not None:
  user_id_constraint = (MyClass.user_id == restrict_user_id)
else:
  user_id_constraint = True
if restrict_month is not None:
  month_constraint = (MyClass.month == restrict_month)
else:
  month_constraint = True
...
return query(MyClass).filter(user_id_constraint and month_constraint and
...)

Yes, this could be written differently, but this pattern comes up fairly
often IME. And it's otherwise very reliable; in numpy in particular 'True
op array' and 'array(True) op array' act identically for every overloaded
binary operator.)

-n
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151124/52fe14f3/attachment-0001.html>


More information about the Python-ideas mailing list