Skip to content Skip to sidebar Skip to footer

How To Implement __delitem__ To Handle All Possible Slice Scenarios?

I work on a class with and embedded list. class a: def __init__(self, n): self.l = [1] * n def __getitem__(self, i): return self.l[i] def __delitem__(se

Solution 1:

The indices method of the slice object will, given the length of the sequence, provide the canonical interpretation of the slice that you can feed to xrange:

def __delitem__(self, item):
    if isinstance(item, slice):
        for i in xrange(*item.indices(len(self.l))):
            print i
    else:
        print operator.index(item)

The use of slice.indices makes sure that you get correct behavior in cases pointed out by Dunes. Also note that you can pass the slice object to list.__delitem__, so if you only need to do some preprocessing and delegate actual deletion to the underlying list, a "naive" del self.l[i] will in fact work correctly.

operator.index will make sure that you get an early exception if your __delitem__ receives a non-slice object that cannot be converted to an index.


Solution 2:

slice objects have start, stop, and step attributes that you can use to get each of those components. For example:

def __delitem__(self, i):
    if isinstance(i, slice):
        for j in xrange(i.start, i.stop, i.step):
            print j
    else:
        print i

Post a Comment for "How To Implement __delitem__ To Handle All Possible Slice Scenarios?"