为什么str(KeyError)会添加额外的引号?

时间:2014-07-28 15:44:25

标签: python exception keyerror

为什么KeyError的字符串表示会在错误消息中添加额外的引号?所有其他内置异常只是直接返回错误消息字符串。

例如,以下代码:

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

产生以下输出:

foo
'foo'

我已尝试使用其他内置异常(IndexErrorRuntimeErrorException等)的示例,并且它们都返回没有引号的异常消息。

help(KeyError)表示__str__(...)定义KeyError,而LookupError定义BaseException__str__(...)使用KeyError基类中定义的{{1}}。这解释了行为是如何不同的,但没有解释为什么 {{1}}在{{1}}中被覆盖。 built-in exceptions上的Python文档没有说明这种差异。

针对Python 2.6.6进行测试

1 个答案:

答案 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将不会打印异常值。

相关问题