为什么KeyError
的字符串表示会在错误消息中添加额外的引号?所有其他内置异常只是直接返回错误消息字符串。
例如,以下代码:
print str(LookupError("foo"))
print str(KeyError("foo"))
产生以下输出:
foo
'foo'
我已尝试使用其他内置异常(IndexError
,RuntimeError
,Exception
等)的示例,并且它们都返回没有引号的异常消息。
help(KeyError)
表示__str__(...)
定义KeyError
,而LookupError
定义BaseException
,__str__(...)
使用KeyError
基类中定义的{{1}}。这解释了行为是如何不同的,但没有解释为什么 {{1}}在{{1}}中被覆盖。 built-in exceptions上的Python文档没有说明这种差异。
针对Python 2.6.6进行测试
答案 0 :(得分:15)
这样做是为了让您可以正确检测KeyError('')
。来自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__().
*/
事实上,如果str(value)
为空字符串,traceback
printing code将不会打印异常值。