Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does str(KeyError) add extra quotes?

Why does the string representation of KeyError add extra quotes to the error message? All other built-in exceptions just return the error message string directly.

For example, the following code:

print str(LookupError("foo"))
print str(KeyError("foo"))

Produces the following output:

foo
'foo'

I have tried this with a sampling of other built-in exceptions (IndexError, RuntimeError, Exception, etc) and they all return the exception message without the quotes.

help(KeyError) says that __str__(...) is defined in KeyError, as opposed to the LookupError, which uses the one defined in the BaseException base class. This explains how the behavior is different, but doesn't explain why __str__(...) is overridden in KeyError. The Python docs on built-in exceptions don't shed any light on this discrepancy.

Tested against Python 2.6.6

like image 962
pzed Avatar asked Jul 28 '14 15:07

pzed


People also ask

How do I fix KeyError in Python?

The Usual Solution: . If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.

What method provides a way to avoid a KeyError message by returning a result when attempting to access keys that may not be present in a dictionary?

Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned.

What does KeyError 2 mean in Python?

The Python "KeyError: 2" exception is caused when we try to access a 2 key in a 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.


Video Answer


1 Answers

This is done so that you can detect KeyError('') properly. From the KeyError_str function source:

/* 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__().
*/

And indeed, the traceback printing code will not print the exception value if str(value) is an empty string.

like image 140
Martijn Pieters Avatar answered Sep 20 '22 09:09

Martijn Pieters