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

Antoine Pitrou solipsis at pitrou.net
Wed Aug 4 15:53:55 CEST 2010


On Wed, 4 Aug 2010 15:39:16 +0200
Łukasz Langa <lukasz at langa.pl> wrote:
> 1. The patch makes KeyError behave analogically to IOError so that the first arg is now a message and the second is the actual key.
> 
> >>> raise KeyError("Key not found", "a Scotsman on a horse")
> Traceback (most recent call last):
> ...
> KeyError: 'Key not found: a Scotsman on a horse'

I suppose you mean
  KeyError: Key not found: 'a Scotsman on a horse'
?

> This is backwards incompatible (which has been addressed for the stdlib in the patch). Now, for non-empty e.args, the key is stored in e.args[-1] whereas it used to in e.args[0]. We could swap the args to make it backwards compatible but then we lose consistency with IOError and the issue on the tracker was originally targetting consistency.

I don't think consistency with IOError is very important. IOError and
KeyError have basically nothing in common.

> 2. Some people suggest adding e.key to KeyError. I like the idea but in my opinion currently it is not implementable in a reliable way.
> 
> a) if the party raising the exception does not pass any arguments, what would the expected behaviour of e.key be? `None` is a valid key so returning this can be misleading.
> 
> b) if the party raising the exception passes one argument, how do we know it's a key and not a message? Take for instance "Set is empty" and such. Presenting e.key = "Set is empty" is just wrong.

As per your patch, all builtins will have been converted to the two
argument form, though, and arguably they are the most common source of
KeyErrors.

> c) if the party raising the exception passes two arguments, we already know which one is the key. So in this case it would work well but at the same time it would be somewhat redundant.

What do you mean? You can certainly use e.args[-1] but it's an ugly and
highly unintuitive notation. I wish the args stuff could die peacefully.

Regards

Antoine.




More information about the Python-Dev mailing list