18

为什么KeyError错误消息的字符串表示形式要多加引号?所有其他内置异常只是直接返回错误消息字符串。

例如,下面的代码:

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

产生以下输出:

foo
'foo'

我已经尝试过使用其他内置异常(IndexErrorRuntimeErrorException等)的样本,它们都返回不带引号的异常消息。

help(KeyError)表示__str__(...)是在 中定义的KeyError,而不是在基类LookupError中定义的。BaseException这解释了行为有何不同,但没有解释为什么 __str__(...)KeyError. 关于内置异常的 Python 文档没有说明这种差异。

针对 Python 2.6.6 测试

4

1 回答 1

23

这样做是为了您可以KeyError('')正确检测。从KeyError_str函数源

/* 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__().
*/

实际上,如果是空字符串,traceback打印代码将不会打印异常值。str(value)

于 2014-07-28T15:48:46.777 回答