Handling exceptions inside context managers
<p>I have some code where I try to reach a resource but sometimes it is unavailable, and results in an exception. I tried to implement a retry engine using <strong>context managers</strong>, but I can't handle the exception raised by the caller inside the <code>__enter__</code> context for my context manager.</p>

<pre><code>class retry(object):
    def __init__(self, retries=0):
        self.retries = retries
        self.attempts = 0
    def __enter__(self):
        for _ in range(self.retries):
            try:
                self.attempts += 1
                return self
            except Exception as e:
                err = e
    def __exit__(self, exc_type, exc_val, traceback):
        print 'Attempts', self.attempts
</code></pre>

<p>These are some examples which just raise an exception (which I expected to handle)</p>

<pre><code>&gt;&gt;&gt; with retry(retries=3):
...     print ok
... 
Attempts 1
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 2, in &lt;module&gt;
NameError: name 'ok' is not defined
&gt;&gt;&gt; 
&gt;&gt;&gt; with retry(retries=3):
...     open('/file')
... 
Attempts 1
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 2, in &lt;module&gt;
IOError: [Errno 2] No such file or directory: '/file'
</code></pre>

<p>Is there any way to intercept these exception(s) and handle them inside the context manager?</p>