[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Christopher Barker
My application-level

> exception handling is rarely that close to the file operations,
> it's usually at a much higher level.


With is used for lots of other things, too. Does this same point apply to
other use cases?

For my part, I still find the extra indentation annoying required for with
to work with files, even without a try block around it. :-(

-CHB
-- 
Christopher Barker, PhD (Chris)

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
___
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/4W436HQXLKQTL4ZHHQ7VI7ZFFMJAQD3G/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Chris Angelico
On Fri, Apr 9, 2021 at 8:22 AM Ethan Furman  wrote:
>
> On 4/8/21 2:40 PM, Chris Angelico wrote:
>
> > At least in this form, it's clear that there's a sharp distinction
> > between the stuff around the outside of the 'with' block and the stuff
> > inside it.
> >
> > The semantics, as suggested, give 'with' blocks two distinct
> > exception-management scopes, which mostly but do not entirely overlap.
> > It's not a problem to rigorously define the semantics, but as
> > evidenced here, people's intuitions will vary depending on which
> > context manager is being used. It's absolutely obvious that the OP's
> > example should let you catch errors from open(), and equally obvious
> > that suppressing BaseException should mean that nothing gets caught.
> > That's the problem here.
> >
> > As such, I'm -0.5 on this. It's a kinda nice feature, but all it
> > really offers is one less indentation level, and the semantics are too
> > confusing.
>
> I, on the other hand, would love for something along those lines -- I find it 
> massively annoying to have to wrap a
> with-block, which is supposed to deal with exceptions, inside a try/except 
> block, because the exceptions that `with`
> deals with are too narrowly focused.
>
> Of course, I also prefer
>
>def positive(val):
>"silly example"
>if val > 0:
>return True
>else:
>return False
>
> over
>
>def positive(val):
>"silly example"
>if val > 0:
>return True
>return False
>
> because the first more clearly says "either this happens, or that happens".  
> Likewise, having the excepts line up with
> the `with` visually ties the code together.
>
> Granted, this mostly boils down to personal preference.
>

And MY preference there would be "return val > 0" :) But I get your point.

If it weren't for the potential confusion, I would absolutely agree
with you. But look at the way for-else loops get treated. They have a
VERY important place, yet they are constantly misunderstood. This
would be worse, and it doesn't have as strong a place.

ChrisA
___
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/URHTU7XOBIK2IUS5P3VRNOBDNXWCIYUR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Greg Ewing

On 9/04/21 2:59 am, anthony.flury via Python-ideas wrote:
I was wondering whether a worthwhile extension might be to allow the 
`with` statement to have an `except` and `else` clauses


I don't think I would find this very useful. My application-level
exception handling is rarely that close to the file operations,
it's usually at a much higher level.

--
Greg

___
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/OHZFRDHZZRLH25IXNUSQXFIF734I5773/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Ethan Furman

On 4/8/21 2:40 PM, Chris Angelico wrote:


At least in this form, it's clear that there's a sharp distinction
between the stuff around the outside of the 'with' block and the stuff
inside it.

The semantics, as suggested, give 'with' blocks two distinct
exception-management scopes, which mostly but do not entirely overlap.
It's not a problem to rigorously define the semantics, but as
evidenced here, people's intuitions will vary depending on which
context manager is being used. It's absolutely obvious that the OP's
example should let you catch errors from open(), and equally obvious
that suppressing BaseException should mean that nothing gets caught.
That's the problem here.

As such, I'm -0.5 on this. It's a kinda nice feature, but all it
really offers is one less indentation level, and the semantics are too
confusing.


I, on the other hand, would love for something along those lines -- I find it massively annoying to have to wrap a 
with-block, which is supposed to deal with exceptions, inside a try/except block, because the exceptions that `with` 
deals with are too narrowly focused.


Of course, I also prefer

  def positive(val):
  "silly example"
  if val > 0:
  return True
  else:
  return False

over

  def positive(val):
  "silly example"
  if val > 0:
  return True
  return False

because the first more clearly says "either this happens, or that happens".  Likewise, having the excepts line up with 
the `with` visually ties the code together.


Granted, this mostly boils down to personal preference.

--
~Ethan~
___
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/3JIGEJAEAJIQXITUCMSKH2ZOK6WSUGJS/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Chris Angelico
On Fri, Apr 9, 2021 at 6:41 AM Ethan Furman  wrote:
>
> On 4/8/21 1:21 PM, Chris Angelico wrote:
> > On Fri, Apr 9, 2021 at 6:16 AM Ethan Furman wrote:
> >> On 4/8/21 11:25 AM, Chris Angelico wrote:
>
> >>> Similar question: What would be the semantics of this?
> >>>
> >>> with contextlib.suppress(BaseException):
> >>>   a = b / c
> >>> except BaseException as e:
> >>>   print(e)
> >>>
> >>> What types of exception could be caught and what types couldn't?
> >>
> >> Well, if every exception is derived from BaseException (they are) and 
> >> contextlib.suppress(BaseException) suppresses all
> >> BaseException-derived exceptions (it does) then the semantics of the above 
> >> are:
> >>
> >> - "a" will be the result of "b / c" if no exception occurs
> >> - otherwise, "a" will be whatever it was before the with-block
> >> - no exception will ever be caught by the except-clause
> >>
> >> Generally speaking, no exception that a context manager handles (i.e. 
> >> suppresses) will ever be available to be caught.
> >
> > What about NameError looking up contextlib, or AttributeError looking
> > up suppress? Will they be caught by that except clause, or not?
>
> Ah, good point -- those two would get caught, as they happen before 
> contextlib.suppress() gets control.
>
> > Thank you for making my point: your assumption is completely the
> > opposite of the OP's, given the same syntactic structure.
>
> The guidance should be:  `try with` behaves exactly as `try/except with a 
> with`, meaning that NameError and
> AttributeError for those two reasons would still be caught.  Yes, it's easy 
> to miss that at first glance, but it's just
> as easy to miss in the traditional try/except layout:
>
> ```python
> try:
>  with contextlib.suppress(BaseException):
>  # do stuff
> except BaseException as e:
>  print(e)
> ```
>
> How many people are going to look at that and think, "oh, NameError and 
> AttributeError can still be caught" ?
>

At least in this form, it's clear that there's a sharp distinction
between the stuff around the outside of the 'with' block and the stuff
inside it.

The semantics, as suggested, give 'with' blocks two distinct
exception-management scopes, which mostly but do not entirely overlap.
It's not a problem to rigorously define the semantics, but as
evidenced here, people's intuitions will vary depending on which
context manager is being used. It's absolutely obvious that the OP's
example should let you catch errors from open(), and equally obvious
that suppressing BaseException should mean that nothing gets caught.
That's the problem here.

As such, I'm -0.5 on this. It's a kinda nice feature, but all it
really offers is one less indentation level, and the semantics are too
confusing.

ChrisA
___
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/3GGA3QLJCBJVRDCYU2HQS4K5DHLJ65TV/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Adding syntax for the empty set

2021-04-08 Thread ucodery
Hello,

I would like to propose adding literal syntax to allow creation of an empty set 
without the need to call the type constructor. I believe the best choice for 
such a literal, and one that has been proposed before, is `{,}`.

I know this idea has surfaced a few times before, but I cannot find any serious 
consideration since the 3K ideas chain with the closest to a pronouncement here 
https://mail.python.org/pipermail/python-3000/2006-May/001599.html. In that 
thread the idea of a new syntax for the empty set did not seem to be rejected 
outright, but more that the idea of set literals at all was still in question 
and as empty sets were not implemented for 2.7 they were ultimately still left 
out of 3k, intentionally or unintentionally.

Within cpython itself `set()` is used just over 200 times to assign a variable 
the value of an empty set. As a comparison `dict()` is used only 15 times, and 
all but one of those are within the test module, mostly for testing dict. On 
the other hand, `{}` is used for assignment a little over 1300 times; I think 
there is a clear preference for using literal over type construction when 
possible. 

I have a working implementation of this new syntax at 
https://github.com/ucodery/cpython/tree/empty-set which includes a few changes. 
Python from this branch allows `{,} == set()` but also `[,] == list()` and `(,) 
== tuple`.  Partly this was because the grammar changes were easier to do all 
three but also because I personally liked keeping some symmetry between these 
collection literals. The main point of starting this thread is to gather 
opinions on adding `{,}` to the language, but I would like to discuss the other 
two as well.

As a secondary point, I do think that this new tuple syntax would make teaching 
python easier. Those new to python often believe that parentheses are what make 
a tuple and only later, if ever, realize that it is only value(s) followed by a 
comma that construct a tuple and that parentheses are places around it mainly 
for readability. This misunderstanding often leads to a bug like  `iter((4))`, 
assuming the programmer meant `iter((4,))`. I believe this confusion about 
whether it is the parentheses or the commas that construct a tuple is deepened 
because two parentheses  surrounding nothing _does_ specifically create the 
empty tuple but `empty = ,` is a SyntaxError. With this literal tuple change, 
those new to the language can be told that parentheses containing at least one 
comma always creates a tuple (at least anywhere is is grammatically valid to 
have a tuple).

Jeremy
___
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/TUCSR7C5K7A4Z62564CTYRR2C6VNGEQ4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Ethan Furman

On 4/8/21 1:21 PM, Chris Angelico wrote:

On Fri, Apr 9, 2021 at 6:16 AM Ethan Furman wrote:

On 4/8/21 11:25 AM, Chris Angelico wrote:



Similar question: What would be the semantics of this?

with contextlib.suppress(BaseException):
  a = b / c
except BaseException as e:
  print(e)

What types of exception could be caught and what types couldn't?


Well, if every exception is derived from BaseException (they are) and 
contextlib.suppress(BaseException) suppresses all
BaseException-derived exceptions (it does) then the semantics of the above are:

- "a" will be the result of "b / c" if no exception occurs
- otherwise, "a" will be whatever it was before the with-block
- no exception will ever be caught by the except-clause

Generally speaking, no exception that a context manager handles (i.e. 
suppresses) will ever be available to be caught.


What about NameError looking up contextlib, or AttributeError looking
up suppress? Will they be caught by that except clause, or not?


Ah, good point -- those two would get caught, as they happen before 
contextlib.suppress() gets control.


Thank you for making my point: your assumption is completely the
opposite of the OP's, given the same syntactic structure.


The guidance should be:  `try with` behaves exactly as `try/except with a with`, meaning that NameError and 
AttributeError for those two reasons would still be caught.  Yes, it's easy to miss that at first glance, but it's just 
as easy to miss in the traditional try/except layout:


```python
try:
with contextlib.suppress(BaseException):
# do stuff
except BaseException as e:
print(e)
```

How many people are going to look at that and think, "oh, NameError and 
AttributeError can still be caught" ?

--
~Ethan~
___
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/KANA7OVE4VLYZWWDCRTCO6F6GQDZ3XZ2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Chris Angelico
On Fri, Apr 9, 2021 at 6:16 AM Ethan Furman  wrote:
>
> On 4/8/21 11:25 AM, Chris Angelico wrote:
>
> > Similar question: What would be the semantics of this?
> >
> > with contextlib.suppress(BaseException):
> >  a = b / c
> > except BaseException as e:
> >  print(e)
> >
> > What types of exception could be caught and what types couldn't?
>
> Well, if every exception is derived from BaseException (they are) and 
> contextlib.suppress(BaseException) suppresses all
> BaseException-derived exceptions (it does) then the semantics of the above 
> are:
>
> - "a" will be the result of "b / c" if no exception occurs
> - otherwise, "a" will be whatever it was before the with-block
> - no exception will ever be caught by the except-clause
>
> Generally speaking, no exception that a context manager handles (i.e. 
> suppresses) will ever be available to be caught.
>

What about NameError looking up contextlib, or AttributeError looking
up suppress? Will they be caught by that except clause, or not?

Thank you for making my point: your assumption is completely the
opposite of the OP's, given the same syntactic structure.

ChrisA
___
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/E3C5T727AWFPYVBVNPQSQNRL4CLKAKRP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Ethan Furman

On 4/8/21 11:25 AM, Chris Angelico wrote:


Similar question: What would be the semantics of this?

with contextlib.suppress(BaseException):
 a = b / c
except BaseException as e:
 print(e)

What types of exception could be caught and what types couldn't?


Well, if every exception is derived from BaseException (they are) and contextlib.suppress(BaseException) suppresses all 
BaseException-derived exceptions (it does) then the semantics of the above are:


- "a" will be the result of "b / c" if no exception occurs
- otherwise, "a" will be whatever it was before the with-block
- no exception will ever be caught by the except-clause

Generally speaking, no exception that a context manager handles (i.e. 
suppresses) will ever be available to be caught.

--
~Ethan~
___
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/6MECZSWSSBIJUTZQWLKSCJKO7PRZA5WT/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Chris Angelico
On Fri, Apr 9, 2021 at 1:38 AM anthony.flury via Python-ideas
 wrote:
> ... indented twice just to accommodate the outer try block.
>
> 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.
>

Normally I'd be -1 on proposals whose main benefit is "one fewer
indentation level". We don't need complexity that serves no other
purpose than that. But the with/try combination is somewhat special -
the 'with' block is inherently about exception handling.

But there's this big question:

On Fri, Apr 9, 2021 at 2:24 AM Paul Bryan  wrote:
> Q. Safe to assume this would catch exceptions from both the call to `open` as 
> well as the call to `open.__enter__`?

No, not safe to assume. It's equally reasonable to define it as
guarding only the body of the statement, or as guarding the header as
well. The semantics have to be locked in one way or the other, and
half the time that's going to be incorrect.

IMO this would be a bug magnet on the difference between "exceptions
that get handed to __exit__" and "exceptions that get caught by the
associated except clause". For instance, what happens in this
situation:

with database_transaction(conn) as self.trn:
self.trn.execute("insert blah blah blah")
else:
with database_transaction(conn) as self.trn:
self.trn.execute("update set blah blah blah")

(Yes, I know a good few database engines have a robust upsert/merge
operation, but bear with me here.) The else clause implies that its
body will not be executed if any exception was raised. But which of
these exceptions would prevent that else from happening?

* NameError on database_transaction or conn
* ConnectionLostError inside database_transaction()
* MemoryError in the transaction's __enter__()
* AttributeError assigning to self.trn
* ResourceError during the __del__ of the previous trn (freebie - that
should be ignored regardless)
* KeyboardInterrupt after assigning to self.trn but before beginning the block
* QueryConflictError inside execute() (another freebie - obviously
this one should)
* CommitFailedError in __exit__, after no other exception
* RollbackFailedError in __exit__, after some other exception

(And yes, RollbackFailed is almost a freebie as well, since I have an
"else" and no "except" here, but that'd be different with some actual
except clauses, so it's worth clarifying.)

If it's defined as simply nesting the with inside a try, then the
answer is "all of the above". But that would be inconsistent with the
existing meaning, which wouldn't cover nearly as much.

Similar question: What would be the semantics of this?

with contextlib.suppress(BaseException):
a = b / c
except BaseException as e:
print(e)

What types of exception could be caught and what types couldn't?

ChrisA
___
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/6TWIPTXPKYMQ7D5RT3YOYMBMI5DHZU32/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Paul Bryan
I think I like it.

Q. Safe to assume this would catch exceptions from both the call to
`open` as well as the call to `open.__enter__`?

Q. What about something even more verbose (descriptive) like`try with
open(...) as cfg:`?  🙂

Paul


On Thu, 2021-04-08 at 15:59 +0100, anthony.flury via Python-ideas
wrote:
> We are all familiar with the `with` statement for context managers,
> so that the resources are correctly finalized/closed in case of an
> exception either in terms
> of the resources being allocated of the processing.
> It is very common though to wrap the `with block` in an outer `try`
> block, since although we know that the resource has been closed, at
> an 'application' level it is still neccessary
> to deal with the exception - an example might be : 
> 
> > 
> > try:
> >     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')
> > 
> It struck me that this is probably quite a common idiom, and we have
> the main processing (of the opened resources) indented twice just to
> accommodate
> the outer try block.
> 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 am not good enough with core development to put together a working
> prototype, but I can imagine that this simple extension would be
> worth while, but I would be more than happy to author a PEP for this
> if it gets some initial positive feedback.
> Open questions - that I have - should we allow `except`, `else` and
> `finally` clauses (or just `except` and `else` - do we need `finally`
> here).
> -- 
> Anthony Flury
> Moble: +44 07743 282707
> Home: +44 (0)1206 391294
> email: anthony.fl...@btinternet.com    
> ___
> 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/ITNCZD2GOQS7TQF7XYFWFYABDP5ZNS5G/
> Code of Conduct: http://python.org/psf/codeofconduct/

___
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/BG3RT7F7FKCBURC45HCBQXPZL4FPOAOD/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Python Idea - extension of 'with'

2021-04-08 Thread Jonathan Goble
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/


[Python-ideas] Python Idea - extension of 'with'

2021-04-08 Thread anthony.flury via Python-ideas
We are all familiar with the `with` statement for context managers, so 
that the resources are correctly finalized/closed in case of an 
exception either in terms

of the resources being allocated of the processing.

It is very common though to wrap the `with block` in an outer `try` 
block, since although we know that the resource has been closed, at an 
'application' level it is still neccessary

to deal with the exception - an example might be :


   try:
    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')

It struck me that this is probably quite a common idiom, and we have the 
main processing (of the opened resources) indented twice just to accommodate

the outer try block.

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 am not good enough with core development to put together a working 
prototype, but I can imagine that this simple extension would be worth 
while, but I would be more than happy to author a PEP for this if it 
gets some initial positive feedback.


Open questions - that I have - should we allow `except`, `else` and 
`finally` clauses (or just `except` and `else` - do we need `finally` here).


--

Anthony Flury
*Moble*: +44 07743 282707
*Home*: +44 (0)1206 391294
*email*: anthony.fl...@btinternet.com 
<>___
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/ITNCZD2GOQS7TQF7XYFWFYABDP5ZNS5G/
Code of Conduct: http://python.org/psf/codeofconduct/