I have an iterator that returns context managers.
I want a pythonic with statement, that emulates the behaviour of several nested with statements, one for each context manager returned by the iterator.
One could say, I want a generalisation of the (deprecated) contextlib.nested function.
contextlib.nestedhas two major problems that caused it to be deprecated.__init__or__new__, and these exceptions would cause the whole with statement to abort without calling__exit__of the outer manager.Truein__exit__, the block should still be executed. But in the implementation ofnested, it just raises aRuntimeErrorwithout executing the block. This problem probably requires a total rewrite ofnested.But it is possible to solve the first problem by just removing one
*in the definition ofnested!This changes the behaviour such that
nesteddoesn’t accept argument lists anymore (which isn’t useful anyway becausewithcan handle that already) but only an iterator. I therefore call the new version “iter_nested“.The user can then define an iterator that instantiates the context managers during iteration.
An example with a generator:
The difference between the codes of the original and my changed version of
nestedis here: