Python raise Message KeyError with color

KeyError messages KeyError not KeyError be managed in the same way as other errors. For example, if I want to use colors, it will work for IndexError , but not for KeyError :

 err_message = '\x1b[31m ERROR \x1b[0m' print err_message raise IndexError(err_message) raise KeyError(err_message) 

Any idea why? And is there a way around it? (I really need an exception of type KeyError to raise, to catch it later)

+6
source share
1 answer

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.

+4
source

Source: https://habr.com/ru/post/948261/


All Articles