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

标签 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 个反斜杠)

最佳答案

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/

相关文章:

python - 如何防止 C 共享库在 python 的标准输出上打印?

python - 如何将支柱变量的内容添加到带有 salt 的文件中?

python - 从 Pandas 数据框中的现有数据创建一个新变量

python - CRC-CCITT 16位Python手动计算

Python 'if x is None' 未捕获 NoneType

python - Tensorflow 磁贴抛出 TypeError : List of Tensors when single Tensor expected

performance - 为什么 `pickle.dump` +`pickle.load` IPC 这么慢,还有快速的替代方案吗?

python - python 数据框删除重复项

python - 以下是在 Python Mechanize 中按下提交按钮的结果

python - 如何为 PyCharm 分配目录