Sujet : Re: Best use of "open" context manager
De : learn2program (at) *nospam* gmail.com (Alan Gauld)
Groupes : comp.lang.pythonDate : 06. Jul 2024, 13:43:40
Autres entêtes
Message-ID : <mailman.5.1720266224.2981.python-list@python.org>
References : 1 2
User-Agent : Mozilla Thunderbird
On 06/07/2024 11:49, Rob Cliffe via Python-list wrote:
If the file does not exist I want to take appropriate action, e.g.
print an error message and abort the program.
I might write it like this:
try:
with open(FileName) as f:
for ln in f:
print("I do a lot of processing here")
# Many lines of code here .....
except FileNotFoundError:
print(f"File {FileName} not found")
sys.exit()
but this violates the principle that a "try" suite should be kept small,
The try is small, it only has a single statement inside.
The compound block inside that statement should have its
own try/ecxepts but the outer one really only applies to
the with statement.
I certainly prefer this option to any of the others presented.
not to mention that having "try" and "except" far apart decreases
readability.
This is a valid concern although that's part of the reason
we use indentation. Compared to early BASIC and FORTRAN with massive
GOSUB type leaps (and often no indentation) it's very readable!
But its still preferable to having the multi-level indents below
or having to remember to close the file when finished (and
ensure that all possible paths do so.
try:
f = open(FileName) as f:
FileLines = f.readlines()
except FileNotFoundError:
print(f"File {FileName} not found")
sys.exit()
# I forgot to put "f.close()" here -:)
Exactly! That's why using with is safer even if the
except is detached from the try.
You are also reading the entire file into memory which could
be an issue. And you are not catching any errors in the
read operations because the except only covers a missing
file.
Really I would like to write something like
try:
with open(FileName) as f:
except FileNotFoundError:
print(f"File {FileName} not found")
sys.exit()
else: # or "finally:"
for ln in f:
print("I do a lot of processing here")
# Many lines of code here .....
I find that much less readable because the file handling
block is a long way from the open file line and has extra
control statements to mentally negotiate.
The advantage of the original version is that you can
ignore errors and read the code easily. You only need
to find the except clause if you need to know how errors
will be dealt with. But if comprehending the core
functionality of the code you can just ignore all
the error handling blocks.
Is there a better / more Pythonic solution?
All IMHO of course, but I think the current implementation
is the best of the options presented.
-- Alan GAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/http://www.amazon.com/author/alan_gauldFollow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos