Python: If Condition then skip to return
<p>I wondered if there is a nice way to tell the python interpreter to <strong>skip to the next/last return statement of a function</strong>.</p>

<p>Lets assume the following dummy code:</p>

<pre class="lang-py prettyprint-override"><code>def foo(bar):
  do(stuff)

  if condition:
    do(stuff)
    if condition2:
      do(stuff)
      if condition3:
        ...

  return (...)
</code></pre>

<p>Sometimes this gets really messy with many conditions that i cant chain because they rely on on the block <code>do(stuff)</code> above. I could now do this:</p>

<pre class="lang-py prettyprint-override"><code>def foo(bar):
  do(stuff)

  if not condition: return (...)
  do(stuff)
  if not condition2: return (...)
  do(stuff)
  if not condition3: return (...)
    ...

  return (...)
</code></pre>

<p>It looks a little less messy but i would have to repeat the return statement again and again which is somwhat anoying and if its a long tuple or similar it even looks worse.
The perfect solution would be to say "if not condition, skip to the final return statement". Is this somehow possible?</p>

<p><strong>edit:</strong> to make this clear: my goal is to improve readability while avoiding a drop in performance</p>

<p>I think I would create a list of functions (I assume that all the <code>do(stuff)</code> in your example are actually different functions). Then you can use a <code>for</code> loop:</p>

<pre><code>list_of_funcs = [func1, func2, func3]
for func in list_of_funcs:
    func(stuff)
    if not condition:
        break
return (...)
</code></pre>

<p>If the conditions are different then you can also create a list of conditions (which will be a list of functions that return <code>True</code> or <code>False</code>), then you can use <code>zip</code> in the following manner:</p>

<pre><code>list_of_funcs = [func1, func2, func3]
list_of_conditions = [cond1, cond2, cond3]
for func, cond in zip(list_of_funcs, list_of_conditions):
    func(stuff)
    if not cond():
        break
return (...)
</code></pre>

<p>This way your actual code stays the same length and in the same indentation level, no matter how many functions and conditions you may have.</p>

python return indentation