On Mon, Jul 29, 2019 at 3:51 PM Eric Fahlgren ericfahlgren@gmail.com wrote:
On Mon, Jul 29, 2019 at 2:58 PM Guido van Rossum guido@python.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 and you get
UnboundLocalError: f
...
-- --Guido van Rossum (python.org/~guido) Pronouns: he/him/his **(why is my pronoun here?) http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-c...