1

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?

4

1 回答 1

2

KeyError是适当的例外。

如果可能,请使用 Python 异常,尤其是适用于第 3 方的 API。这节省了进口和学习曲线。

您可以简化代码:

if not my_dict.viewkeys() >= set(expected_keys):
    raise KeyError

或简单地访问所有密钥:

for key in expected_keys:
    my_dict[key]  # test for presence early

或者只是不测试并让使用密钥的代码引发异常。

于 2013-04-21T13:24:45.543 回答