The behavior of these exceptions is different. KeyError performs the following actions on the transmitted message
If args is a tuple of exactly one item, apply repr to args[0]. This is done so that eg 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__().
To do this, you can use the following workaround: Create your own class with the inscription :
eg
class X(str): def __repr__(self): return "'%s'" % self raise KeyError(X('\x1b[31m ERROR \x1b[0m'))
but I really donβt understand why this is necessary ... I think that @BorrajaX comment is the best solution.
source share