为什么在 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 个反斜杠)
最佳答案
ValueError
和 KeyError
的 __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/