[Python-ideas] with ... except

Antoine Pitrou solipsis at pitrou.net
Fri Mar 8 16:16:25 CET 2013


Le Fri, 8 Mar 2013 14:48:34 +0000,
Oscar Benjamin
<oscar.j.benjamin at gmail.com> a écrit :
> 
> > 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()

That's true, but only if the two things are strongly related, not in
the general case.

Regards

Antoine.





More information about the Python-ideas mailing list