[Python-ideas] Block-Scoped Exception Handlers

Nick Coghlan ncoghlan at gmail.com
Thu May 5 22:17:52 EDT 2016


On 6 May 2016 at 05:17, Kyle Lahnakoski <klahnakoski at mozilla.com> wrote:
> May you provide me with an example of how contextmanager would help with
> the indentation?

contextmanager doesn't, ExitStack does (which is in the standard
library for 3.3+, and available via contextlib2 for earlier versions).

> From what little I can glean, Python2.7 already has
> this, and I use it, but I do not see how replacing `try` blocks with
> `with` blocks reduces indentation.   I do agree it looks cleaner than a
> `try/except` block though.

One of the cases that ExitStack handles is when you want to unwind all
the contexts at the same point in the code, but enter them at
different points. It does that by letting you write code like this:

    with ExitStack() as cm:
        cm.enter_context(the_first_cm)
        # Do some things
        cm.enter_context(the_second_cm)
        # Do some more things
        cm.enter_context(the_third_cm)
        # Do yet more things
    # All three context managers get unwound here

The nested with equivalent would be:

    with the_first_cm:
        # Do some things
        with the_second_cm:
            # Do some more things
            with the_third_cm:
                # Do yet more things
    # All three context managers get unwound here

As an added bonus, the ExitStack approach will also let you push
arbitrary callbacks, enter contexts conditionally, and a few other
things. Barry Warsaw has an excellent write-up here:
http://www.wefearchange.org/2013/05/resource-management-in-python-33-or.html

Cheers,
Nick.

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


More information about the Python-ideas mailing list