@@ -56,21 +56,18 @@ Functions provided:
5656
5757 Combine multiple context managers into a single nested context manager.
5858
59- Code like this::
59+ This function has been deprecated in favour of the multiple manager form
60+ of the :keyword: `with ` statement.
61+
62+ The one advantage of this function over the multiple manager form of the
63+ :keyword: `with ` statement is that argument unpacking allows it to be
64+ used with a variable number of context managers as follows::
6065
6166 from contextlib import nested
6267
63- with nested(A(), B(), C()) as (X, Y, Z ):
68+ with nested(*managers ):
6469 do_something()
6570
66- is equivalent to this::
67-
68- m1, m2, m3 = A(), B(), C()
69- with m1 as X:
70- with m2 as Y:
71- with m3 as Z:
72- do_something()
73-
7471 Note that if the :meth: `__exit__ ` method of one of the nested context managers
7572 indicates an exception should be suppressed, no exception information will be
7673 passed to any remaining outer context managers. Similarly, if the
@@ -80,8 +77,29 @@ Functions provided:
8077 :meth: `__exit__ ` methods should avoid raising exceptions, and in particular they
8178 should not re-raise a passed-in exception.
8279
80+ This function has two major quirks that have led to it being deprecated. Firstly,
81+ as the context managers are all constructed before the function is invoked, the
82+ :meth: `__new__ ` and :meth: `__init__ ` methods of the inner context managers are
83+ not actually covered by the scope of the outer context managers. That means, for
84+ example, that using :func: `nested ` to open two files is a programming error as the
85+ first file will not be closed promptly if an exception is thrown when opening
86+ the second file.
87+
88+ Secondly, if the :meth: `__enter__ ` method of one of the inner context managers
89+ raises an exception that is caught and suppressed by the :meth: `__exit__ ` method
90+ of one of the outer context managers, this construct will raise
91+ :exc: `RuntimeError ` rather than skipping the body of the :keyword: `with `
92+ statement.
93+
94+ Developers that need to support nesting of a variable number of context managers
95+ can either use the :mod: `warnings ` module to suppress the DeprecationWarning
96+ raised by this function or else use this function as a model for an application
97+ specific implementation.
98+
8399 .. deprecated :: 3.1
84- The with-statement now supports this functionality directly.
100+ The with-statement now supports this functionality directly (without the
101+ confusing error prone quirks).
102+
85103
86104.. function :: closing(thing)
87105
0 commit comments