title: Catching exception in context manager __enter__()
body: <p>Is it possible to ensure the <code>__exit__()</code> method is called even if there is an exception in <code>__enter__()</code>?  </p>
  
  <pre><code>&gt;&gt;&gt; class TstContx(object):
  ...    def __enter__(self):
  ...        raise Exception('Oops in __enter__')
  ...
  ...    def __exit__(self, e_typ, e_val, trcbak):
  ...        print "This isn't running"
  ... 
  &gt;&gt;&gt; with TstContx():
  ...     pass
  ... 
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;stdin&gt;", line 3, in __enter__
  Exception: Oops in __enter__
  &gt;&gt;&gt; 
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <p>This is as close as I could get...</p>
  
  <pre><code>class TstContx(object):
      def __enter__(self):
          try:
              # __enter__ code
          except Exception as e
              self.init_exc = e
  
          return self
  
      def __exit__(self, e_typ, e_val, trcbak):
          if all((e_typ, e_val, trcbak)):
              raise e_typ, e_val, trcbak
  
          # __exit__ code
  
  
  with TstContx() as tc:
      if hasattr(tc, 'init_exc'): raise tc.init_exc
  
      # code in context
  </code></pre>
  
  <p>In hind sight, a context manager might have not been the best design decision </p>