[Python-ideas] with ... except
Antoine Pitrou
solipsis at pitrou.net
Fri Mar 8 11:33:42 CET 2013
Le Fri, 8 Mar 2013 11:24:02 +0100,
Masklinn <masklinn at masklinn.net> a écrit :
> On 2013-03-08, at 11:13 , Antoine Pitrou wrote:
>
> > Hello,
> >
> > 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
> >
> > or:
> >
> > try:
> > with transaction.commit_on_success():
> > ...
> > except ObjectDoesNotExist:
> > # do something else, perhaps clean up some internal cache
> >
> >
> > How about adding syntax sugar for the above, in the form of a
> > with ... except clause? It would nicely reduce spurious
> > indentation, as with the try / except / finally which, long ago(!),
> > helped reduce indentation and typing by removing the need to nest a
> > try / except inside a try / finally.
>
> Isn't it essentially the same suggestion as Alan Johnson's last week?
> http://mail.python.org/pipermail/python-ideas/2013-March/019730.html
Hmm, I hadn't read that thread. "try with" looked sufficiently ugly
that I wasn't interested :-)
But anyway it seems that discussion was conflating a lot of things. I
would only like a shortcut for a "try ... except" around a "with",
without any other sophistication. Seems "with" is essentially a
"try ... finally", there seems to be a syntactic precedent already.
And, yes, I actually want to catch exceptions raised *inside* the
"with" block, not just by the "with" statement itself. The database
example above makes it clear: I want the "with" to issue a ROLLBACK on
an exception inside the block, *and* I want to handle the exception in
a specific way after the ROLLBACK.
Regards
Antoine.
More information about the Python-ideas
mailing list