Explanation for the second case that made contextlib.nested to be deprecated (Python documentation)
<p><code>context.nested</code> is deprecated, I'm trying to understand the rationale behind this and after reading the documentation for a quite long time, I couldn't see an example to make the second issue clear: </p>

<blockquote>
  <p>Secondly, if the <code>__enter__()</code> method of one of the inner context managers raises an exception that is caught and suppressed by the <code>__exit__()</code> method of one of the outer context managers, this construct will raise <code>RuntimeError</code> rather than skipping the body of the <code>with</code> statement.</p>
</blockquote>

<p>First what is the meaning of inner context managers and outer context managers here? What would this look like in code? </p>

<p><strong>Edit:</strong></p>

<p>From what I understood, I tried to deomonstrate the issue with code: </p>

<pre><code>&gt;&gt;&gt; class A:
...     def __enter__(*args):  
...             print("enter A")
...     def __exit__(*args): print("exit A"); return True
...

&gt;&gt;&gt; class B:
...     def __enter__(*args): print("B __enter__") 
...     def __exit__(*args): raise Exception("spam")
...
&gt;&gt;&gt; with nested(A(), B()): pass  # A() outer context, B() inner context? 
...
enter A
B __enter__
exit A
</code></pre>

<p>But this code doesn't raise <code>RuntimeError</code>?</p>

<p>In your example, you have the context manager <code>B</code> raising exception in the <code>__exit__</code> method.  But the quote describes the inner exception being raised by the <code>__enter__</code> method.  I was able to reproduce a <code>RuntimeError</code> by moving the raised exception to the <code>__enter__</code> method.</p>

<p>FWIW, the replacement for <code>contextlib.nested</code> is <a href="https://docs.python.org/3.4/library/contextlib.html#contextlib.ExitStack" rel="nofollow"><code>ExitStack</code></a> in python 3.4+.  There is a <a href="http://contextlib2.readthedocs.org/en/latest/" rel="nofollow">backport</a> for python2.</p>

python