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

Stefan Behnel stefan_ml at behnel.de
Sun Mar 3 20:50:28 CET 2013

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.

        f = open("somefile.txt")
    except FileNotFoundError:
        raise   # or return, or whatever

    with f:

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.


More information about the Python-ideas mailing list