[Python-ideas] with ... except

Masklinn masklinn at masklinn.net
Fri Mar 8 11:24:02 CET 2013


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



More information about the Python-ideas mailing list