Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python raise KeyError message with color

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)

like image 878
Thomas Leonard Avatar asked Jun 27 '13 18:06

Thomas Leonard


People also ask

How do you raise a KeyError in Python?

A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.

When should I raise my KeyError?

Python KeyError is raised when we try to access a key from dict, which doesn't exist.

How do I fix KeyError in Python?

When working with dictionaries in Python, a KeyError gets raised when you try to access an item that doesn't exist in a Python dictionary. This is simple to fix when you're the one writing/testing the code – you can either check for spelling errors or use a key you know exists in the dictionary.

What does KeyError 2 mean in Python?

The Python "KeyError: 2" exception is caused when we try to access a 2 key in a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.


1 Answers

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.

like image 69
oleg Avatar answered Sep 29 '22 15:09

oleg