[Python-ideas] [Python-ideos] Dedicated overloadable boolean operators
MRAB
python at mrabarnett.plus.com
Tue Nov 24 16:47:07 EST 2015
On 2015-11-24 21:24, Greg Ewing wrote:
> Brendan Barnwell wrote:
>> On 2015-11-23 22:34, Random832 wrote:
>>
> >> C# allows overloading the short-circuit operators
>>>
>>> a and b: a if a.__false__() else a & b
>>> a or b: a if a.__true__() else a | b
>>>
>> The problem is that this kind of overriding doesn't handle the main
>> use case, which is elementwise and-ing/or-ing.
>
> Maybe we can hook into __bool__ somehow, though?
>
> Suppose 'a and b' were treated as:
>
> try:
> result = bool(a)
> except IDoNotShortCircuit:
> result = a.__logical_and___(b)
> else:
> if not result:
> result = b
>
> Since a __bool__ call is required anyway, this
> shouldn't slow down the case where there is no
> overriding.
>
That still doesn't deal with the issue of what should happen if the
order is reversed, e.g. "numpy_array and simple_bool" vs "simple_bool
and numpy_array", where "numpy_array" has the non-shortcircuiting
behaviour but "simple_bool" hasn't.
More information about the Python-ideas
mailing list