I'm creating an open source project on Github and I want to make sure I do everything I can to make it robust, stable and that its Pythonic. To this end, I have a question about what kind of exception I should use when I expect a key to exist in a dictionary and it is not included.
That is, the calling function would be something like:
def calling_func():
my_dict = {
'value_1': 1,
'value_2': None,
'value_3': '3',
}
foo(my_dict)
My function foo
expects the dictionary to contain the key
(and corresponding value
), value_4
. Would it be appropriate to raise KeyError
in the following case?
def foo(my_dict):
expected_keys = ['value_1', 'value_2', 'value_3', 'value_4']
for key in expected_keys:
if key not in my_dict:
raise KeyError
It seems the traditional use for KeyError
is the inverse of this usage.
Should I create my own exception type for this?
class MissingKeyError(Exception):
pass
Or something to this effect?