26.07.19 23:46, MRAB пише:
On 2019-07-26 19:26, Serhiy Storchaka wrote:
[snip]
I propose to add "except" clause to "for" and "with" statement to catch
exceptions in the code that can't be wrapped with "try ... except".
for VAR in EXPR:
BLOCK
except EXC:
HANDLER
should be equivalent to
try:
_it = iter(EXPR)
except EXC:
HANDLER
else:
while True:
try:
VAR = next(_it)
except StopIteration:
break
except EXC:
HANDLER
break
BLOCK
[snip]
1. The 'for' loop can have an 'else' clause, and so can the 'try'
statement. Is there any ambiguity over its meaning?
An 'else' clause is already have different meanings in different
statements: 'if', 'try' and 'while'/'for'. This proposition does not add
anything new to this.
If an exception is not raised in 'for' or 'with' then its body is
executed. So no need to add an 'else' clause in the meaning of 'try'.
There will be no conflict between two 'else'.
2. In your example you have it catching the exception if EXPR or
iter(EXPR) raises. Is that a good idea?
Definitely we should catch the exception if EXPR is raised in the 'with'
statement, because different content managers can acquire resources
either in `__enter__` or in constructor (like open()). There is less
confidence about 'for', but I think that it is better to catch it,
because iter() is called implicitly and there is no way to catch an
exception in it. iter() can raise an exception:
>>> f = open('python')
>>> f.close()
>>> iter(f)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
But all this is discussable.
_______________________________________________
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/NCBMXN6N7HDDXGPTJ2O374BEJ7JQ7DR2/
Code of Conduct: http://python.org/psf/codeofconduct/