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

Andrew Barnert abarnert at yahoo.com
Tue Nov 24 02:15:16 EST 2015


On Nov 23, 2015, at 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.

Actually, it _is_ possible in C++. You can pretty much do anything in C++, as long as you're an expert, you don't care about anyone reading your code, and you don't mind 1970s-style build times, and this is no exception. You just write an expression template library that uses non-short-circuiting-at-compile-time operators to generate functions that are short-circuiting at runtime, and then add the boilerplate to wrap any constants or normal variables up into your expression template types, and you're set.

A simpler solution is to use lambda lifting, like Swift: "a and b" just means "a.__and__(lambda: b)".

You could also split the operator into two method calls, without combining with bool conversion a la C#. So "a and b" becomes "tmp = a.__and1__()", then "tmp.__and2__(b) if tmp2 else tmp2". That way, "and" can return a non-boolean value, just as it does when not overloaded. I can't think of any language that does this off the top of my head, but I'm sure they exist.

Or, in languages with macros or equivalent, you just use a macro instead of a function.

Or, in languages with lazy evaluation by default, it's even simpler--if you don't use the result of "b" anywhere, it never gets evaluated.




More information about the Python-ideas mailing list