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?
The Python or operator is short-circuitingWhen evaluating an expression that involves the or operator, Python can sometimes determine the result without evaluating all the operands. This is called short-circuit evaluation or lazy evaluation. For example: x or y. If x is truthy, then the or operator returns x .
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first ...
Short-circuiting the evaluation of an expression means that only a part of the expression needs to be evaluated before finding its value. For example: a == null || a.size() == 0.
Yep, both and and or operators short-circuit -- see the docs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With