On Thu, Apr 8, 2021, 11:39 AM anthony.flury via Python-ideas <
python-ideas@python.org> wrote:

> I was wondering whether a worthwhile extension might be to allow the
> `with` statement to have an `except` and  `else` clauses which would have
> the same
>
> semantics as wrapping the `with` block with a try - for example the above
> would now look like:
>
>
> with open('config.cfg', 'r') as cfg:
>     # Process the open  file
>     config = load_config(cfg)
> except FileNotFound:
>     logging.info('Config file not found - using default configuration')
> except PermissionError:
>     logging.warning('Cannot open config .cfg - using default
> configuration')
>     config = default_config()
> else:
>     logging.info('Using config from config.cfg')
>
> Treating the 'with' as an implied `try` would reduce the march to the
> right - now the key processing of the resource is now indented only one
> level - and the association of the exception
> from the `with` block is syntactically clear.
>

I like the concept, but I don't like just having a plain with block
implicitly acting as a try block because you have to read further to
actually understand that yes, you're catching exceptions here.

What about "try with ...:"? The combination of the two keywords fits the
"try-with-resources" pattern in some other languages and makes it explicit
up front that exceptions are about to be caught, while keeping just one
level of indentation.

>
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GMJO63QEYLRDF6X3DUKVKKRMFK3VAIIY/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to