Why does the string representation of KeyError
add extra quotes to the error message? All other built-in exceptions just return the error message string directly.
For example, the following code:
print str(LookupError("foo"))
print str(KeyError("foo"))
Produces the following output:
foo
'foo'
I have tried this with a sampling of other built-in exceptions (IndexError
, RuntimeError
, Exception
, etc) and they all return the exception message without the quotes.
help(KeyError)
says that __str__(...)
is defined in KeyError
, as opposed to the LookupError
, which uses the one defined in the BaseException
base class. This explains how the behavior is different, but doesn't explain why __str__(...)
is overridden in KeyError
. The Python docs on built-in exceptions don't shed any light on this discrepancy.
Tested against Python 2.6.6
The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.
Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned.
The Python "KeyError: 2" exception is caused when we try to access a 2 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.
This is done so that you can detect KeyError('')
properly. From the KeyError_str
function source:
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
And indeed, the traceback
printing code will not print the exception value if str(value)
is an empty string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With