On Tue, 30 Jul 2019 at 04:00, Ethan Furman <ethan@stoneleaf.us> wrote:
> If this "with...except" leads to more robust code then I think many would like to use it, but not if it's confusing as that would lead to less robust code.
For me, "it's for robust code" is sufficient hint that I now remember
what it does (much the same way that "it's for search loops" is the
hint I need for for...else). And when I'm trying to write robust code,
I *do* worry about exceptions in the with expression, and the fact
that I can't easily catch them. So for me, this is definitely a real
(albeit one I can usually ignore) problem.
I'm not sure I understand the desire to catch every possible exception right where it occurs. I've never felt this need somehow. *Apart from open()* can someone give me an example from real code where a context manager is likely to raise an exception that can meaningfully be handled?
I've re-read Serhiy's original example, involving a context manager for connecting to a socket and a for-loop for reading the data from the socket and writing it to another one (all three operations that may fail), but I find it unconvincing. For reference I'm copying it here again:
with connect() as stream: # connect() or __enter__() can fail.
for data in stream: # __next__() can fail
write(data) # write() can fail
This very much looks like toy networking code to me -- real networking code is always written in a completely different way, using different abstractions that raise different exceptions, and I don't think it would be written in this style even if `with` and `for` had optional `except` clauses. (Alternatively, you can write little wrappers that turn OSError into different exceptions so you can use a single try/except/except/except statement to handle them all.)
--