Serhiy Storchaka writes:
A year or two ago I proposed the same syntax with different semantic: to catch only exceptions in the context manager, not in the with block.
FWIW, this is the semantics I would expect, for the reason you give:
Exceptions in the with block you can catch by adding try/except around the with block, exceptions in the with block and the context manager you can catch by adding try/except around the with statement, but there is no currently way to catch only exceptions in the context manager.
Does this apply to the necessary setup in any other syntactic constructs? For example, in the abstract this is a "problem" in 'for':
for i in :
... for j in 2: ... pass ... Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: 'int' object is not iterable
it's not possible to catch the TypeError *only* in the outer loop. Of course this isn't a "real" problem in 'for', since this TypeError is surely not an exceptional situation you need to catch and handle at runtime, it's just a bug.
I guess the biggest difference is that in 'with' the setup (corresponding to calling 'iter' on the iterable in 'for') is specified to be arbitrary code and can be arbitrarily complex. 'with' is the only construct where that's true, that I know of. (Of course the setups for other syntactic constructs are very simple.) Is that so?