r/ProgrammerTIL • • Sep 12 '17

Python [Python] TIL that you can chain comparisons

69 Upvotes

16 comments sorted by

View all comments

Show parent comment

4

u/cdrini Sep 12 '17 edited Sep 13 '17

I think the reason Python has comparison chaining is because it goes very well with "The Zen of Python". if 0 < x < 10: is much more beautiful and simple than if 0 < x and x < 10:. I would say writing the latter knowing the former exists is bad code style. (Apparently PyCharm suggests this as well, but only for monotonic chains; PEP8 doesn't mention it).

This feature is pretty rare. I learned about the fact that Python supports this while reading the Julia documentation (Julia also supports comparison chaining). I did some searching and it looks like Perl 6, Mathematica, and Lisp (actually only supports monotonic chaining: (<= 0 x 10)) support comparison chaining. (stackoverflow:language-support-for-chained-comparison)

My guess as to why it isn't very common would be because of the 'standard' set by C and because it makes parsing more complex. In C, 0 < x < 10 is evaluated as (0 < x) < 10 => 1 < 10 => 1. JavaScript and even C++ behave in the same way, while C# and Java throw errors. My guess would be parsing becomes a little annoying since 0 < x can be a bool or... something else depending on whether it's followed by another relational operator, but I'm not too sure how that works. (enwiki:Relational_operator#Operator_chaining)

In short, yes, the generalization can lead to messy code if used incorrectly, but if we can trust children to use the < and > operators sanely in math, then I think we can trust programmers to do so, too :)

E: a word; correction

2

u/sim642 Sep 13 '17

I simply feel like Python should restrict the chaining to monotone sequences because that's the only practical and unambiguously understandable use of the syntax.

1

u/j-frost Sep 27 '17

JavaScript (as usual) actually doesn't behave very well. For instance,

j-frost@1 ~ node
> -1 < 0 < 1
false

because -1 < 0 === true and since true == 1, true < 1 === false.