[Python-ideas] with ... except

Antoine Pitrou solipsis at pitrou.net
Fri Mar 8 11:13:50 CET 2013


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.

Regards

Antoine.





More information about the Python-ideas mailing list