[英]Why does str(KeyError) add extra quotes?
Why does the string representation of KeyError
add extra quotes to the error message? 为什么
KeyError
的字符串表示形式会在错误消息中添加额外的引号? 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. 我已尝试使用其他内置异常(
IndexError
, RuntimeError
, Exception
等)的IndexError
,并且它们都返回没有引号的异常消息。
help(KeyError)
says that __str__(...)
is defined in KeyError
, as opposed to the LookupError
, which uses the one defined in the BaseException
base class. help(KeyError)
说, __str__(...)
中定义KeyError
,而不是在LookupError
,它使用在所定义的一个BaseException
基类。 This explains how the behavior is different, but doesn't explain why __str__(...)
is overridden in KeyError
. 这解释了行为是如何不同的,但没有解释为什么在
KeyError
重写了__str__(...)
。 The Python docs on built-in exceptions don't shed any light on this discrepancy. 关于内置异常的Python文档并没有说明这种差异。
Tested against Python 2.6.6 针对Python 2.6.6进行了测试
This is done so that you can detect KeyError('')
properly. 这样做是为了您可以正确检测
KeyError('')
。 From the KeyError_str
function source : 从
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__().
*/
And indeed, the traceback
printing code will not print the exception value if str(value)
is an empty string. 实际上,如果
str(value)
是一个空字符串,则traceback
打印代码不会打印异常值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.