[Python-ideas] with-statement syntactic quirk

Nick Coghlan ncoghlan at gmail.com
Sun Nov 4 16:41:35 CET 2012

On Mon, Nov 5, 2012 at 12:32 AM, Barry Warsaw <barry at python.org> wrote:
> On Nov 02, 2012, at 08:41 AM, Nick Coghlan wrote:
>>> Go's "defer" is quite a neat solution for these hassles if anyone's in
>>the mood for a time machine discussion.
>>> http://golang.org/doc/effective_go.html#defer
>>Go was one of the reference points for the ExitStack design (it's a large
>>part of why the API also supports providing callbacks directly to the exit
>>stack, not just as context managers).
> Is it fair to say that the difference between Go's defer and ExitStack is that
> the latter gives you the opportunity to clean up earlier than at function
> exit?

Yep. You can also do some pretty interesting things with ExitStack
because of the pop_all() operation (which moves all of the registered
operations to a *new* ExitStack instance).

I wrote up a few of the motivating use cases as examples and recipes
in the 3.3 docs:

I hope to see more interesting uses over time as more people explore
the possibilities of a dynamic tool for composing context managers
without needing to worry about the messy details of unwinding them
correctly (ExitStack.__exit__ is by far the most complicated aspect of
the implementation).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list