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>Refactoring your code is a <em>much</em> better idea than what I am about to suggest, but this is an option.</p>

<pre><code>class GotoEnd(Exception):
    pass

def foo(bar):

  try:
    do(stuff)
    if not condition: raise GotoEnd
    do(stuff)
    if not condition2: raise GotoEnd

    do(stuff)
    if not condition3: raise GotoEnd

    ...
  except GotoEnd:
    pass

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

python return indentation