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

标签 python exception keyerror

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

例如下面的代码:

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

产生以下输出:

foo
'foo'

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

help(KeyError)__str__(...) 是在 KeyError 中定义的,而不是 LookupError,它使用 BaseException 基类中定义的那个。这解释了行为有何不同,但没有解释为什么 __str__(...)KeyError 中被覆盖。 built-in exceptions 上的 Python 文档不要阐明这种差异。

针对 Python 2.6.6 进行了测试

最佳答案

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

事实上,traceback printing code如果 str(value) 是空字符串,则不会打印异常值。

关于python - 为什么 str(KeyError) 添加额外的引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24998968/

相关文章:

python - Healpy map2alm 和 alm2map 错误

python - 在 numpy masked_array 中用 nan 替换 masked

c++ - 引发异常:读取访问冲突this-> pCurr为0xDDDDDDDD

java - 从 Java 中的 toString 方法捕获异常

分配时 Python 字典键错误 - 我该如何解决这个问题?

Python 注释不同输入情况的返回类型

python - 将 H2O 模型导入 Python

java - 尽管类型相同,但我收到了一个 ClassCastException 事件。为什么?

python - key 错误 : 0 Pandas