These Exceptions' behavior are different. KeyError does following action with message passed
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__().
One can use following workaround for this: Create own class with repr overrided:
for example
class X(str):
def __repr__(self):
return "'%s'" % self
raise KeyError(X('\x1b[31m ERROR \x1b[0m'))
but I realy don't understand Why this can be needed... I think @BorrajaX comment is better solution.