Why does str (KeyError) add extra quotes?

Why KeyError string representation add extra quotation marks to the error message? All other built-in exceptions simply return an error message string directly.

For example, the following code:

 print str(LookupError("foo")) print str(KeyError("foo")) 

It produces the following output:

 foo 'foo' 

I tried this with a selection of other built-in exceptions ( IndexError , RuntimeError , Exception , etc.) and they all return an exception message without quotes.

help(KeyError) says that __str__(...) is defined in KeyError , unlike LookupError , which uses the one defined in the BaseException base class. This explains how the behavior is different, but does not explain why __str__(...) overridden in KeyError . Python docs on built-in exceptions do not shed light on this inconsistency.

Tested in Python 2.6.6

+7
python exception keyerror
source share
1 answer

This is done to correctly detect KeyError('') . From source KeyError_str :

 /* If args is a tuple of exactly one item, apply repr to args[0]. This is done so that eg 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__(). */ 

Indeed, the traceback print code will not print the exception value if str(value) is an empty string.

+11
source share

All Articles