I was testing out comparison chaining and I noticed that in certain patterns the some of the function calls are not executed.
If I plan on using the function calls to do things what would be the best way to ensure that they are executed while still being concise? (is this considered a bad practice)
def foo(bar):
print(f"\tbar")
return bar
a = b = False
print (f"one = {foo(a)==foo(b)==True}")
print (f"two = {True==foo(a)==foo(b)}")
print (f"three = {foo(a)==True==foo(b)}")
a = True
print (f"one = {foo(a)==foo(b)==True}")
print (f"two = {True==foo(a)==foo(b)}")
print (f"three = {foo(a)==True==foo(b)}")
a = b = True
print (f"one = {foo(a)==foo(b)==True}")
print (f"two = {True==foo(a)==foo(b)}")
print (f"three = {foo(a)==True==foo(b)}")
Output:
bar
bar
one = False
bar < only executes once
two = False
bar < only executes once
three = False
bar
bar
one = False
bar
bar
two = False
bar
bar
three = False
bar
bar
one = True
bar
bar
two = True
bar
bar
three = True
note: reviewing the suggested questions I saw how-do-chained-comparisons-in-python-actually-work
... In summary, essentially Python then does this:
stack_1 = stack_2 = input('Value:')
if 1 < stack_1:
result = False
else:
result = stack_2 < 10
with the stack_* values cleared again.
The stack, then, holds the unnamed intermediate result to compare martijn-pieters