[Python-ideas] with ... except

Antoine Pitrou solipsis at pitrou.net
Sat Mar 9 11:45:26 CET 2013


On Fri, 8 Mar 2013 11:01:27 -0800
Andrew Barnert <abarnert at yahoo.com> wrote:

> On Mar 8, 2013, at 7:16, Antoine Pitrou <solipsis at pitrou.net> wrote:
> 
> > 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.
> 
> I think his point is that if you need any specific case often enough in your app, they will be related, and you can write a single context manager that wraps up your specific case so you can use it. In other words, messy with and try statements can be refactored into functions as needed, very easily.

Of course, you are right in some way. But it's a bit of a shame to have
to resort to a helper function because the syntax isn't powerful
enough :-)

Regards

Antoine.





More information about the Python-ideas mailing list