[Python-ideas] One-line "try with" statement

Nick Coghlan ncoghlan at gmail.com
Mon Mar 4 09:22:26 CET 2013

On Mon, Mar 4, 2013 at 5:50 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Andrew Barnert, 03.03.2013 14:24:
>> For example, if you do "with open(path) as f:" the context manager
>> doesn't (and shouldn't) do anything to protect you from a
>> FileNotFoundError in the open, or an IOError reading inside the block.
>> If you want to, say, log, or try a backup file, how else would you
>> handle that but a with inside a try?
> If you really care about errors when opening the file (i.e. when creating
> the context manager), then the correct way to do this is to only wrap the
> creation of the context manager in a try-except clause, i.e.
>     try:
>         f = open("somefile.txt")
>     except FileNotFoundError:
>         do_stuff()
>         raise   # or return, or whatever
>     with f:
>         do_other_stuff()
> Otherwise, you risk accidentally catching (and potentially shadowing)
> exceptions that originated from the body of the with statement instead of
> just the context manager creation.
> This may look a bit overly complicated for a file, but it quickly becomes
> more obvious for more complex context managers, e.g. those that may raise
> more common errors like ValueError or AttributeError.

Indeed - complex try blocks in general are a red flag when paired with
exception handlers for common exceptions.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list