Is this better for a method that allows you to raise several types of exceptions, or just one?

My question is about the best (most “Putin's”) exception handling when the method can raise two (or more) types of exceptions, but their interpretation is the same from the perspective of the caller.

Suppose I have a collection of named (name is string) objects. I want this collection to be able to return elements by index or by name.

class CollectionOfNamedItems:
    def __init__(self, items):
        self._dict = {item.name: item for item in items} 
        self._items = tuple(items)

    def __getitem__(self, item):
        if isinstance(item, str):
            return = self._dict[item]  # may raise KeyError
        return self._items[item]  # may raise IndexError

# usage: collection['X'] or collection[1]

My question is this: depending on whether we access the element by index or by name, methods __getitem__raise IndexErroror KeyError. Is this a good way to make exceptions? The caller of this method would have to catch these two types of exceptions. Or it would be better (more pythonic to say) to catch KeyErrorboth IndexErrorinside __getitem__and raise ValueError(or some other?), So that the caller could catch only one type of exception, regardless of the type of argument passed.

    def __getitem__(self, item):
        try:
            if isinstance(item, str):
                return = self._dict[item]  # may raise KeyError
            return self._items[item]  # may raise IndexError
        except (KeyError, IndexError):
            raise ValueError('invalid item')

On the other hand, it seems logical to quit TypeErrorwhen I call collection[1.5]or collection[None]. This is because I feel that the interpretation is different from the errors above.

I would be grateful for any comments or ideas on this topic.

+4
2

, . , , - . ValueError .

, , __getitem__ IndexError KeyError. ?

, . , , "" "" .

. , /, / , . . , .

, , , , CollectionOfNamedItems, " ", __getitem__ IndexError . , , .

" ".

.

, KeyError IndexError LookupError, , , LookupError:

try:
    item = collection[id]
except LookupError:
    # Could be KeyError or IndexError, we don't care.
+6

Pythonic . . , . , . , , .

0

All Articles