[Python-Dev] Iterator version of contextlib.nested
hfuerstenau at gmx.net
Fri Jun 12 17:18:18 CEST 2009
contextlib.nested has recently been deprecated on grounds of being
unnecessary now that the with statement accepts multiple context
managers. However, as has been mentioned before
doesn't cover the case of a variable number of context managers, i.e.
with contextlib.nested(*list_of_managers) as list_of_results:
It was suggested that in these use cases a custom context manager should
be implemented. However, it seems that such an implementation would be
an almost exact copy of the present code for "nested".
I'm proposing to add an iterator version of "nested" to contextlib
(possibly called "inested"), which takes an iterable of context managers
instead of a variable number of parameters. The implementation could be
taken over from the present "nested", only changing "def
nested(*managers)" to "def inested(managers)".
This has the advantage that an iterator can be passed to "inested", so
that each context managers is created in the context of all previous
ones, which was one of the reasons for introducing the multi-with
statement in the first place. "contextlib.inested" would therefore be
the generalization of the multi-with statement to a variable number of
managers (and "contextlib.nested" would stay deprecated).
More information about the Python-Dev