gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:01:33 43 4
gpt4 key购买 nike

为什么 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/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com