That is definitely an ambiguity worth considering (whether __enter__ is
within the implied 'try').

Anecdotally, I showed the with/except example to my student (who's
relatively new to python), to see how he interpreted it. He (correctly?)
assumed the CM operations were within the 'try', and was pretty surprised
when I told him that the except part of the with wasn't actually valid
Python.

On Tue, Jan 22, 2019 at 2:30 PM Chris Angelico <ros...@gmail.com> wrote:

> On Wed, Jan 23, 2019 at 7:11 AM Paul Ferrell <pfl...@gmail.com> wrote:
> > As a result, I would like to propose that the syntax for 'with' blocks
> > be changed such that they can be accompanied by 'except', 'finally',
> > and/or 'else' blocks as per a standard 'try' block. These would handle
> > exceptions that occur in the 'with' block, including the execution of
> > the applicable __enter__ and __exit__ methods.
> >
> > Example:
> >
> > try:
> >     with open(path) as myfile:
> >       ...   # Do stuff with file
> > except (OSError, IOError) as err:
> >     logger.error("Failed to read/open file {}: {}".format(path, err)
> >
> > The above would turn into simply:
> >
> > with open(path) as myfile:
> >     ... # Do stuff with file
> > except (OSError, IOError) as err:
> >     logger.error(...)
>
> Edge case: The "try/with/except" structure includes the entire 'with'
> header inside the try block, including the call to open(). But if the
> with block itself is handling the exceptions, the expression
> "open(path)" is actually evaluated before the exception handling gets
> going. So adding an except clause is NOT the same as just adding
> another context manager to the stack.
>
> I'm -0.25 on it, as I don't think overlaying in this way improves
> clarity. The current syntax makes it very obvious that the
> "open(path)" call is inside the try/except, but the proposed syntax
> isn't so clear (and as many people will expect it to be inside as
> outside).
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>


-- 
Paul Ferrell
pfl...@gmail.com
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to