为什么str(KeyError)会添加额外的引号?

pze*_*zed 13 python exception keyerror

为什么字符串表示为KeyError错误消息添加额外的引号?所有其他内置异常只是直接返回错误消息字符串.

例如,以下代码:

print str(LookupError("foo"))
print str(KeyError("foo"))
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

foo
'foo'
Run Code Online (Sandbox Code Playgroud)

我曾与其他内置异常的采样(试过这个IndexError,RuntimeError,Exception等),他们都没有引号返回异常消息.

help(KeyError)表示它__str__(...)定义于KeyError,而不是LookupError使用BaseException基类中定义的那个.这解释了行为是如何不同的,但没有解释为什么 __str__(...)被覆盖KeyError.关于内置异常的Python文档并没有说明这种差异.

针对Python 2.6.6进行了测试

Mar*_*ers 17

这样做是为了让您可以KeyError('')正确检测.从KeyError_str功能来源:

/* 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)

实际上,如果是空字符串,则traceback打印代码不会打印异常值str(value).

  • 可能也是这样你可以从`KeyError('3')`告诉`KeyError(3)`,它允许你看到什么时候将错误的类型传递给映射. (5认同)