2

I found this code in a 3rd party module which was ignoring foo[::step] or key.step in this case.

def __getitem__(self, key):
    if isinstance(key, slice):
        return self._sub_slice(key.start, key.stop)
    if self._is_in_range(key):
        return self._tree[key]
    else:
        raise KeyError(key)

While supporting steps would be ideal, assuming this isn't going to be supported, I'd like to add an exception, otherwise foo[a:b:-1] for eg will ignore the -1 in the slice.

eg:

if key.step not in {None, 1}:
    raise Exception("only a step size of 1 is supported")

So my question is, for valid but unsupported slice steps, which exception type should be used?

ideasman42
  • 42,413
  • 44
  • 197
  • 320
  • 2
    Note that an unsupplied step size defaults to `None`, not `1`. – user2357112 Nov 07 '15 at 20:39
  • 1
    I'd recommend making your own `SliceStepError` class; the built-in ones don't match very well. – bbayles Nov 07 '15 at 20:39
  • 1
    Correct me if I'm misunderstanding, but slicing doesn't usually raise an exception. Accessing an index out of range will, but the slicing won't. Let me know if this is helpful: http://stackoverflow.com/a/9490148/1832539 – idjaw Nov 07 '15 at 20:39

1 Answers1

2

ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

https://docs.python.org/3/library/exceptions.html#ValueError

"The right type but an inappropriate value" seems to match your description pretty well.

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143