[Python-ideas] with ... except

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Mar 8 15:48:34 CET 2013


On 8 March 2013 10:13, Antoine Pitrou <solipsis at pitrou.net> wrote:
>
> A common pattern for me is to write a with statement for resource
> cleanup, but also handle specific errors after that. Right now, this is
> a bit cumbersome:
>
>   try:
>       with open("somefile", "rb)" as f:
>           ...
>   except FileNotFoundError:
>       # do something else, perhaps actually create the file

In some cases it might be reasonable to make a context manager that
handles errors from the original context manager e.g.:

import contextlib

@contextlib.contextmanager
def handle(errorcls, func, *args, **kwargs):
    try:
        yield
    except errorcls:
        func(*args, **kwargs)

with handle(FileNotFoundError, print, 'error'), open('somefile', 'rb') as f:
    print('No error')

> or:
>
>   try:
>       with transaction.commit_on_success():
>           ...
>   except ObjectDoesNotExist:
>       # do something else, perhaps clean up some internal cache

Another possibility is a context manager that handles both things, e.g.:

@contextmanager
def commit_or_clean(errorcls):
    try:
        with transaction.commit_on_success():
            yield
    except errorcls:
        clean()


Oscar



More information about the Python-ideas mailing list