Changeset 391 for python/trunk/Doc/library/contextlib.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/contextlib.rst
r2 r391 7 7 8 8 .. versionadded:: 2.5 9 10 **Source code:** :source:`Lib/contextlib.py` 11 12 -------------- 9 13 10 14 This module provides utilities for common tasks involving the :keyword:`with` … … 59 63 Combine multiple context managers into a single nested context manager. 60 64 61 Code like this:: 65 This function has been deprecated in favour of the multiple manager form 66 of the :keyword:`with` statement. 67 68 The one advantage of this function over the multiple manager form of the 69 :keyword:`with` statement is that argument unpacking allows it to be 70 used with a variable number of context managers as follows:: 62 71 63 72 from contextlib import nested 64 73 65 with nested( A(), B(), C()) as (X, Y, Z):74 with nested(*managers): 66 75 do_something() 67 68 is equivalent to this::69 70 m1, m2, m3 = A(), B(), C()71 with m1 as X:72 with m2 as Y:73 with m3 as Z:74 do_something()75 76 76 77 Note that if the :meth:`__exit__` method of one of the nested context managers … … 83 84 should not re-raise a passed-in exception. 84 85 86 This function has two major quirks that have led to it being deprecated. Firstly, 87 as the context managers are all constructed before the function is invoked, the 88 :meth:`__new__` and :meth:`__init__` methods of the inner context managers are 89 not actually covered by the scope of the outer context managers. That means, for 90 example, that using :func:`nested` to open two files is a programming error as the 91 first file will not be closed promptly if an exception is thrown when opening 92 the second file. 93 94 Secondly, if the :meth:`__enter__` method of one of the inner context managers 95 raises an exception that is caught and suppressed by the :meth:`__exit__` method 96 of one of the outer context managers, this construct will raise 97 :exc:`RuntimeError` rather than skipping the body of the :keyword:`with` 98 statement. 99 100 Developers that need to support nesting of a variable number of context managers 101 can either use the :mod:`warnings` module to suppress the DeprecationWarning 102 raised by this function or else use this function as a model for an application 103 specific implementation. 104 105 .. deprecated:: 2.7 106 The with-statement now supports this functionality directly (without the 107 confusing error prone quirks). 85 108 86 109 .. function:: closing(thing)
Note:
See TracChangeset
for help on using the changeset viewer.