[Python-Dev] Exception Reorg PEP checked in (original) (raw)

Wilfredo Sánchez Vega wsanchez at apple.com
Thu Sep 8 02:06:08 CEST 2005


(sorry for the delayed reply; vacation)

On Aug 14, 2005, at 12:27 PM, Guido van Rossum wrote:

On 8/14/05, Michael Hudson <mwh at python.net> wrote:

Wilfredo Sánchez Vega <wsanchez at wsanchez.net> writes:

I'm curious about why Python lacks FileNotFoundError, PermissionError and the like as subclasses of IOError. Good question. Lack of effort/inertia? Well, I wonder how often it's needed. My typical use is this: try: f = open(filename) except IOError, err: print "Can't open %s: %s" % (filename, err) return and the error printed contains all the necessary details (in fact it even repeats the filename, so I could probably just say "print err").

That's fine for log output, but weak for handling the error.

Why do you need to know the exact reason for the failure? If you simply want to know whether the file exists, I'd use os.path.exists() or isfile(). (Never mind that this is the sometimes-frowned-upon look-before-you-leap; I think it's often fine.)

If you're going to wave off the look-before-you-leap argument, I
guess you're right in that case, but I think it's a pretty valid
argument for a lot of applications. os.path.exists() also has a race
condition in the case where the file is deleted between your test for
is and the subsequent attempt to access it, so you'd still need to
handle that error in the exception handling if you care about
correctness.

I agree that in many (most?) cases, this can be fudged, but if
it's easier to do the correct thing, more people would do the correct
thing.

In any case, os.path.exists() also doesn't catch permissions
errors, and I often find myself wanting to handle those errors
specially as well.

An example where both are useful is in an HTTP server, where a
different status code should be returned to the client depending on
success, file not found, permission denied, and other cases.
Presently, I (and twisted.web) have to check errno in the IOError
exception handler, which is really clunky, and I have to do it fairly
often.

Also note that providing the right detail can be very OS specific. Python doesn't just run on Unix and Windows.

File not found is a detectable error case on all platforms, I
think. On an OS that doesn't have permissions errors, I wouldn't
expect the existence of an exception that isn't used to be a huge
portability problem. I can't imagine that checking errno is a more
portable solution.

These two exist and are quite useful in Java, for whatever that's
worth.

 -wsv

-------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3057 bytes Desc: not available Url : http://mail.python.org/pipermail/python-dev/attachments/20050907/241d7cd0/smime-0001.bin



More information about the Python-Dev mailing list