Sean Nguyen Sean Nguyen - 2 months ago 4
Python Question

Short-circuit evaluation like Python's "and" while storing results of checks

I have multiple expensive functions that return results. I want to return a tuple of the results of all the checks if all the checks succeed. However, if one check fails I don't want to call the later checks, like the short-circuiting behavior of

and
. I could nest
if
statements, but that will get out of hand if there are a lot of checks. How can I get the short-circuit behavior of
and
while also storing the results for later use?

def check_a():
# do something and return the result,
# for simplicity, just make it "A"
return "A"

def check_b():
# do something and return the result,
# for simplicity, just make it "B"
return "B"

...


This doesn't short-circuit:

a = check_a()
b = check_b()
c = check_c()

if a and b and c:
return a, b, c


This is messy if there are many checks:

if a:
b = check_b()

if b:
c = check_c()

if c:
return a, b, c


Is there a shorter way to do this?

wim wim
Answer

Just use a plain old for loop:

results = {}
for function in [check_a, check_b, ...]:
    results[function.__name__] = result = function()
    if not result:
        break

The results will be a mapping of the function name to their return values, and you can do what you want with the values after the loop breaks.

Use an else clause on the for loop if you want special handling for the case where all of the functions have returned truthy results.

Comments