python使用颜色引发KeyError消息

Tho*_*ard 7 python exception keyerror

似乎KeyError消息的管理方式与其他错误不同.例如,如果我想使用颜色,它将适用于IndexError但不适用于KeyError:

err_message = '\x1b[31m ERROR \x1b[0m'

print err_message

raise IndexError(err_message)

raise KeyError(err_message)
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?有没有办法绕过它?(我真的需要KeyError提出类型的例外,以便以后能够捕获它)

ole*_*leg 5

这些例外的行为是不同的.KeyError执行以下操作并传递消息

   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)

可以使用以下解决方法:使用repr覆盖创建自己的类:

例如

class X(str):
    def __repr__(self):
        return "'%s'" % self

raise KeyError(X('\x1b[31m ERROR \x1b[0m'))
Run Code Online (Sandbox Code Playgroud)

但我真的不明白为什么需要这个...我认为@BorrajaX评论是更好的解决方案.