简体   繁体   中英

Why does str(KeyError) add extra quotes?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM