[Python-ideas] ExitStack: Allow exiting individual context managers

Steven D'Aprano steve at pearwood.info
Sun Dec 6 19:32:25 EST 2015


On Sun, Dec 06, 2015 at 11:48:41PM +0200, Ram Rachum wrote:
> Hi guys,
> 
> I'm using `contextlib.ExitStack` today, and pushing context managers into
> it. I find myself wanting to exit specific context managers that I've
> pushed into it, while still inside the `with` suite of the `ExitStack`. In
> other words, I want to exit one of the context managers but still keep the
> `ExitStack`, and all other context managers, acquired. This isn't currently
> possible, right? What do you think about implementing this?

I'm not entirely sure what you mean. Can you give an example?

Some of the examples given here:

https://docs.python.org/3/library/contextlib.html#examples-and-recipes

sound like they might be related to what you are trying to do.

Otherwise, if I have understood your requirement correctly, I think you 
might have a good case for *not* using ExitStack. If you have one 
context manager that you want to treat differently from the others, 
perhaps you should write it differently from the others:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    do_things()
    with open(special_file) as sf:
        do_other_things()
    do_more_things()



-- 
Steven


More information about the Python-ideas mailing list