[Python-ideas] overloading chained comparison

Nathaniel Smith njs at pobox.com
Wed Mar 19 02:56:00 CET 2014


On Wed, Mar 19, 2014 at 12:03 AM, Greg Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Nathaniel Smith wrote:
>
>> This does solve our problematic case above: only 'arr' implements
>> __chain_comparison__, so we have
>>   0 < x < arr
>> becoming
>>   arr.__chain_comparison__([0, x, arr], [operator.lt, operator.lt])
>
>
> I don't see how that works, because you need to evaluate
> arr in order to tell whether it has a __chain_comparison__
> method. So chained comparisons would always have to evaluate
> all operands and could never short-circuit.

Blah, you're absolutely right of course, total brainfart about what
short-circuiting means, even though it was right there in the
disassembly I was looking at.

So yes, I guess the only meaningful part of my message is just the
observation that short-circuiting makes any kind of chained comparison
overload IMHO rather unsatisfying, because it forces you to make the
ugly rule that the special overloading arguments must always occur in
one of the first two positions. Which is probably true by accident 99%
of the time, so as long as short-circuiting exists at all, supporting
chained comparison overload will mean creating an obscure trap.

On the one hand, I am kind of terrified of the idea of code that
depends on short-circuiting here, like:

  0 < x < side_effecting_function_only_called_for_negative_x()

It would be interesting to know how many chained comparisons exist in
the wild with non-trivial 3rd+ arguments.

On the other hand, disabling short-circuiting in general for chained
comparisons would still be a technical compatibility break. Somehow
adding py3's first __future__ feature just for this seems like a lot
to ask...

-n

-- 
Nathaniel J. Smith
Postdoctoral researcher - Informatics - University of Edinburgh
http://vorpus.org


More information about the Python-ideas mailing list