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

Pet*_*rch 3 python python-2.x python-2.7

为什么在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'
Run Code Online (Sandbox Code Playgroud)

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

(注意4个反斜杠)

Mar*_*ers 5

__str__对方法ValueErrorKeyError不同:

>>> str(ValueError(repr('\\')))
"'\\\\'"
>>> str(KeyError(repr('\\')))
'"\'\\\\\\\\\'"'
Run Code Online (Sandbox Code Playgroud)

或使用print:

>>> print str(ValueError(repr('\\')))
'\\'
>>> print str(KeyError(repr('\\')))
"'\\\\'"
Run Code Online (Sandbox Code Playgroud)

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

>>> print str(KeyError(42))
42
>>> print str(KeyError('42'))
'42'
Run Code Online (Sandbox Code Playgroud)

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

>>> print str(KeyError(''))
''
Run Code Online (Sandbox Code Playgroud)

ValueError异常不必处理Python值,它的消息始终是一个字符串.

KeyError_str()CPython源代码中函数:

/* 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__().
*/
Run Code Online (Sandbox Code Playgroud)

ValueError使用默认BaseException_str()函数,对于单参数情况只使用str(arg[0]).