>> raise ValueError("This is an example: %s" % re-6ren">
gpt4 book ai didi

python - 为 KeyError 打印出奇怪的错误消息

转载 作者:太空宇宙 更新时间:2023-11-03 14:15:05 24 4
gpt4 key购买 nike

为什么在 Python 2.7 中会这样

>>> test_string = "a \\test"
>>> raise ValueError("This is an example: %s" % repr(test_string))
ValueError: This is an example: 'this is a \\test'

但是

>>> raise KeyError("This is an example: %s" % repr(test_string))
KeyError: This is an example: 'this is a \\\\test'

(注意 4 个反斜杠)

最佳答案

ValueErrorKeyError__str__ 方法不同:

>>> str(ValueError(repr('\\')))
"'\\\\'"
>>> str(KeyError(repr('\\')))
'"\'\\\\\\\\\'"'

或使用print:

>>> print str(ValueError(repr('\\')))
'\\'
>>> print str(KeyError(repr('\\')))
"'\\\\'"

那是因为 KeyError 显示了你传入的 'key' 的 repr(),所以你可以区分字符串和整数键:

>>> print str(KeyError(42))
42
>>> print str(KeyError('42'))
'42'

或者更重要的是,这样您仍然可以识别空字符串键错误:

>>> print str(KeyError(''))
''

ValueError 异常不必处理 Python 值,它的消息总是字符串。

来自KeyError_str() function in the CPython source code :

/* 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__().
*/

ValueError 使用 default BaseException_str() function ,对于单参数情况仅使用 str(arg[0])

关于python - 为 KeyError 打印出奇怪的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051333/

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