The Python Doc for Comparisons says:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
And these SO questions/answers shed some more light on such usage:
- Python comparison operators chaining/grouping left to right?
- What does "evaluated only once" mean for chained comparisons in Python?, in particular the currently-accepted answer
So something like (contrived example):
if 1 < input("Value:") < 10: print "Is greater than 1 and less than 10"
only asks for input once. This makes sense. And this:
if 1 < input("Val1:") < 10 < input("Val2:") < 20: print "woo!"
only asks for Val2
if Val1
is between 1 & 10 and only prints "woo!" if Val2
is also between 10 and 20 (proving they can be 'chained arbitrarily'). This also makes sense.
But I'm still curious how this is actually implemented/interpreted at the lexer/parser/compiler (or whatever) level.
Is the first example above basically implemented like this:
x = input("Value:")
1 < x and x < 10: print "Is between 1 and 10"
where x
really only exists (and is actually essentially unnamed) for those comparisons? Or does it somehow make the comparison operator return both the boolean result and the evaluation of the right operand (to be used for further comparison) or something like that?
Extending analysis to the second example leads me to believe it's using something like an unnamed intermediate result (someone educate me if there's a term for that) as it doesn't evaluate all the operands before doing the comparison.