Rerun code block in Python
<p>I was looking to try to figure out a way to write something like this:</p>

<pre><code>code_that_should_not_be_run_again()
with rerun_code_that_may_fail():
  another_method(x)
  run_me_again_if_i_fail(y)
code_that_should_only_be_run_if_above_succeeds()
</code></pre>

<p>Where the above would run that code, and catch an exception, if it was caught, then try to run the code, again. here would be a longer version of what I want:</p>

<pre><code>code_that_should_not_be_run_again()
try:
  another_method(x)
  run_me_again_if_i_fail(y)
catch Exception:
  try:
    another_method(x)
    run_me_again_if_i_fail(y)
  catch Exception:
    raise Exception("Couldn't run")
 code_that_should_only_be_run_if_above_succeeds()
</code></pre>

<p>I was thinking I could probably use a generator, maybe catch that yielded content in to a lambda and then run it twice, somehow, but now sure how I can code something like this.</p>

<p>Is this possible in Python? Or maybe something similar to this that can be done?</p>

<p>Here's what I've tried so far:</p>

<pre><code>from contextlib import contextmanager
@contextmanager
def run_code():
    print 'will run'
    try:
      yield
    except SomeException:
      try:
        yield
      except SomeException:
        raise SomeException('couldn't run')
</code></pre>

<p><em>Edit</em> Python wont' let you do what I want to do, so you can only use decorators on functions :(</p>

<p>Using the retry decorator - <a href="https://pypi.python.org/pypi/retry/" rel="nofollow">https://pypi.python.org/pypi/retry/</a> - and under the scenario that you want to catch any <code>TypeError</code>, with a maximum of 3 tries, with a delay of 5 seconds:</p>

<pre><code>from retry import retry

@retry(TypeError, tries=3, delay=5)
def code_block_that_may_fail():
    method_1()
    method_2()
    #Some more methods here...

code_block_that_may_fail()
</code></pre>

<p>Can't get too much cleaner than that. </p>

<p>Additionally, you can use the built-in logger to log failed attempts (see documentation).</p>

python python-2.7 generator yield with-statement