How to raise an IndexError when slice indices are out of range?

。_饼干妹妹 提交于 2019-12-05 08:18:54

In Python 2 you can override __getslice__ method by this way:

class MyList(list):
    def __getslice__(self, i, j):
        len_ = len(self)
        if i > len_ or j > len_:
            raise IndexError('list index out of range')
        return super(MyList, self).__getslice__(i, j)

Then use your class instead of list:

>>> egg = [1, "foo", list()]
>>> egg = MyList(egg)
>>> egg[5:10]
Traceback (most recent call last):
IndexError: list index out of range

There is no silver bullet here; you'll have to test both boundaries:

def slice_out_of_bounds(sequence, start=None, end=None, step=1):
    length = len(sequence)
    if start is None:
        start = 0 if step > 1 else length
    if start < 0:
        start = length - start
    if end is None:
        end = length if step > 1 else 0
    if end < 0:
        end = length - end
    if not (0 <= start < length and 0 <= end <= length):
        raise IndexError()

Since the end value in slicing is exclusive, it is allowed to range up to length.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!