Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you are worried about b or c being functions that are called instead of just variables that are evaluated, then this code shows that short-circuiting is your friend:</p> <pre><code>a = False def b(): print "b was called" return True if a and b(): print "this shouldn't happen" else: print "if b was not called, then short-circuiting works" </code></pre> <p>prints</p> <pre><code>if b was not called, then short-circuiting works </code></pre> <p>But if you have code that does this:</p> <pre><code>a = call_to_expensive_function_A() b = call_to_expensive_function_B() c = call_to_expensive_function_C() if a and b and c: do something... </code></pre> <p>then your code is still calling all 3 expensive functions. Better to let Python be Python:</p> <pre><code>if (call_to_expensive_function_A() and call_to_expensive_function_B() and call_to_expensive_function_C()) do something... </code></pre> <p>which will only call as many expensive functions as necessary to determine the overall condition.</p> <p><strong>Edit</strong></p> <p>You can generalize this using the <code>all</code> built-in:</p> <pre><code># note, this is a list of the functions themselves # the functions are *not* called when creating this list funcs = [function_A, function_B, function_C] if all(fn() for fn in funcs): do something </code></pre> <p>Now if you have to add other functions, or want to reorder them (maybe <code>function_A</code> is very time-consuming, and you would benefit by filtering cases that fail <code>function_B</code> or <code>function_C</code> first), you just update the <code>funcs</code> list. <code>all</code> does short-circuiting just as if you had spelled out the if as <code>if a and b and c</code>. (If functions are 'or'ed together, use <code>any</code> builtin instead.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload