On 30/07/2019 00:07:52, Guido van Rossum wrote:
On Mon, Jul 29, 2019 at 3:51 PM Eric Fahlgren <firstname.lastname@example.org
On Mon, Jul 29, 2019 at 2:58 PM Guido van Rossum <email@example.com <mailto:firstname.lastname@example.org>> wrote: I am *guessing* the problem here is something like this: with open(filename) as f: data = f.read() raises an exception if the open() call fails, but putting try... except IOError: ... around the whole thing also catches I/O errors in the read() call (or anything else you might put in the body). Other solutions are more verbose and run other risks. For other types of context managers it may be worse because the error you want to catch occurs in the __enter__() call that's implicit in the with-clause (for open(), __enter__() is just "return self" since all the work happens before). Isn't the appropriate solution to that one as follows? It's pretty clear what you're trying to do, so the extra couple of lines aren't all that obtrusive. try: f = open('x', 'r') except IOError as whatever: handle whatever else: with f: data = f.read()
It's quite verbose though. And it makes you think "oh, I don't need
with, I can use
finally: f.close()" -- until the IOError hits
Hm, I'm not sure why you would be more likely to think that in this
example than anywhere else where you use an open() context manager.
(Observation: I think once you start using context managers, you
appreciate their advantages and are unlikely to remove one from your
code without good reason. This is certainly a rite of passage I went
through with open().)
I believe the/a motivation for Serhiy's proposal is to write really
robust code, e.g. in a program that must not fail such as a network
server serving multiple clients.
ISTM this is a worthwhile goal, and at present the only way to achieve
it is with somewhat verbose and clunky code.