[Python-Dev] #2651 - KeyError does not round trip strings

Nick Coghlan ncoghlan at gmail.com
Thu Aug 5 14:44:49 CEST 2010


2010/8/5 Fred Drake <fdrake at acm.org>:
> 2010/8/4 Łukasz Langa <lukasz at langa.pl>:
>> Shall we do an e.index for IndexErrors as well?
>
> I don't recall stumbling over that need, but the parallel makes it
> tempting.  I expect is should be a separate patch, though.
>
> Antoine's right about using keyword args from C, though.  I'd expect a
> new helper function that handles this specific case, since it's likely
> to be common.  Whether it used a keyword are or just performed a
> setattr after the exception is created doesn't really matter.

Yeah, helper functions for C code that accepted the extra arguments
would do the trick.

I actually had a look to see what IOError does with its attributes and
I think it qualifies as being a little on the special side (replicated
in both 2.6 and the py3k branch):

>>> io1 = IOError(1)
>>> io2 = IOError(1, 2)
>>> io3 = IOError(1, 2, 3)
>>> io4 = IOError(1, 2, 3, 4)
>>> io1, io2, io3, io4
(IOError(1,), IOError(1, 2), IOError(1, 2), IOError(1, 2, 3, 4))
>>> io1.errno, io2.errno, io3.errno, io4.errno
(None, 1, 1, None)
>>> io1.strerror, io2.strerror, io3.strerror, io4.strerror
(None, 2, 2, None)
>>> io1.filename, io2.filename, io3.filename, io4.filename
(None, None, 3, None)

One argument = no attributes set
Two arguments = errno, strerror set (including if second argument is
explicitly None)
Three arguments = errno, strerror, filename set
Four or more arguments = no attributes set

Keyword arguments are not supported by IOError (or EnvironmentError,
which is where the above behaviour is actually implemented).

That precedent would deem it acceptable to adopt a backwards
compatible protocol that still allowed arbitrary positional arguments
for Key/Attribute/IndexError, but treated the 2 argument case
specially.

However, the IOError behaviour really doesn't strike me as a
particularly good example for us to be following, so PEP 3151 may want
to consider the issue of tidying up those exception signatures.

The "right" way to go still appears to be to allow arbitrary
positional arguments (which go into .args) for backwards
compatibility, then add appropriate keyword-only arguments. IOError
could get some keyword only arguments as well, retaining the somewhat
odd behaviour above for backwards compatibility reasons (although the
repr in the 3 argument case should be fixed).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list