繁体   English   中英

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

[英]Why does str(KeyError) add extra quotes?

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

例如,以下代码:

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

产生以下输出:

foo
'foo'

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

help(KeyError)说, __str__(...)中定义KeyError ,而不是在LookupError ,它使用在所定义的一个BaseException基类。 这解释了行为是如何不同的,但没有解释为什么KeyError重写了__str__(...) 关于内置异常的Python文档并没有说明这种差异。

针对Python 2.6.6进行了测试

这样做是为了您可以正确检测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__().
*/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM