[Python-ideas] Block-Scoped Exception Handlers

Michael Selik michael.selik at gmail.com
Fri May 6 13:28:46 EDT 2016


On Fri, May 6, 2016 at 10:50 AM Kyle Lahnakoski <klahnakoski at mozilla.com>
wrote:

>
> Of course, a couple `try` nested statements make the indentation worse.
> For example, we wish to ignore problems in dealing with todo items, like
> above, but the todo items are complicated; each is a dict() of details.
> Failure to deal with one of the details is ignored, but the rest of the
> details are still attempted:
>
> def process_todo(todo):
> ____pre_process()
> ____for t in todo:
> ________try:
> ____________for u, v in t.items():
> ________________try:
> ____________________process()
> ________________except Exception, e:
> ____________________continue
> ________except Exception, e:
> ____________break
> ____post_process()
>
>
The refactoring that first comes to mind is to make the inner portion a
separate function:

    def process_one(thing):
        for u, v in thing.items():
            try:
                process()
            except Exception as e:
                continue

    def process_group(group):
        pre_process()
        for thing in group:
            try:
                process_one(thing)
            except Exception as e:
                break
        post_process()

This avoids the excessive indentation and helps improve the reading of how
an error in the group will break but an error in one will continue. Does
that not satisfy?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160506/164cb6ee/attachment.html>


More information about the Python-ideas mailing list