What Does "evaluated Only Once" Mean For Chained Comparisons In Python?
A friend brought this to my attention, and after I pointed out an oddity, we're both confused. Python's docs, say, and have said since at least 2.5.1 (haven't checked further back:
Solution 1:
The 'expression' y
is evaluated once. I.e., in the following expression, the function is executed only one time.
>>> def five():
... print 'returning 5'
... return 5
...
>>> 1 < five() <= 5
returning 5
True
As opposed to:
>>> 1 < five() and five() <= 5
returning 5
returning 5
True
Solution 2:
In the context of y being evaluated, y is meant as an arbitrary expression that could have side-effects. For instance:
class Foo(object):
@property
def complain(self):
print("Evaluated!")
return 2
f = Foo()
print(1 < f.complain < 3) # Prints evaluated once
print(1 < f.complain and f.complain < 3) # Prints evaluated twice
Post a Comment for "What Does "evaluated Only Once" Mean For Chained Comparisons In Python?"