Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
Sean Nguyen Avatar asked Sep 20 '16 20:09

Sean Nguyen


People also ask

What is short circuit evaluation in Python programming?

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 .

What do you mean by short circuit evaluation?

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 ...

What does short circuit evaluation of an expression mean explain with an example?

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.

Does Python support short-circuiting in boolean expressions?

Yep, both and and or operators short-circuit -- see the docs.


1 Answers

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.

like image 51
wim Avatar answered Sep 21 '22 09:09

wim