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

时间:2015-12-02 19:29:13

标签: python python-2.7 python-2.x

为什么在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个反斜杠)

1 个答案:

答案 0 :(得分:5)

__str__ValueError的{​​{1}}方法不同:

KeyError

或使用>>> str(ValueError(repr('\\'))) "'\\\\'" >>> str(KeyError(repr('\\'))) '"\'\\\\\\\\\'"'

print

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

repr()

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

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

>>> print str(KeyError('')) '' 例外不必处理Python值,它的消息始终是一个字符串。

来自KeyError_str() function in the CPython source code

ValueError

/* 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__(). */ 使用default BaseException_str() function,对于单参数案例,只使用ValueError

相关问题