Question

It seems that KeyError messages are not managed the same way the other errors are. For example if I want to use colors, it will work for an IndexError but nor for a 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 to bypass it? (I really need a exception of type KeyError to be raised, to be able to catch it later)

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top