为 KeyError 打印出奇怪的错误消息
Strange error message printed out for KeyError
为什么 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 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])
.