为什么str(KeyError)会多出引号?
为什么KeyError
的字符串表示会在错误信息中加上额外的引号?其他内置的异常信息直接返回错误信息字符串,没有这个问题。
比如,下面这段代码:
print str(LookupError("foo"))
print str(KeyError("foo"))
会产生以下输出:
foo
'foo'
我还试过其他一些内置异常(比如IndexError
、RuntimeError
、Exception
等),它们的错误信息都是直接返回,没有引号。
help(KeyError)
显示KeyError
中定义了__str__(...)
,而LookupError
则使用的是BaseException
基类中定义的。这解释了为什么它们的行为不同,但并没有解释为什么在KeyError
中重写了__str__(...)
。关于这个差异,Python文档中的内置异常也没有提供更多信息。
测试版本为Python 2.6.6
1 个回答
27
这样做是为了让你能够正确地检测到 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)
是一个空字符串,就不会打印出异常的值。