How to implement __delitem__ to handle all possible slice scripts?

I am working on a class with and inline list.

class a: def __init__(self, n): self.l = [1] * n def __getitem__(self, i): return self.l[i] def __delitem__(self, i): print type(i) print i 

I want to use the del operator with the full slicing syntax:

 p = a(10) del p[1:5:2] 

__delitem__ gets a slice if the parameter is not a single index. How can I use the slice object to iterate over the specified elements?

+4
source share
2 answers

The indices method of the slice object will, given the length of the sequence, provide a canonical interpretation of the slice, which you can pass 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) 

Using slice.indices ensures correct behavior in cases marked by dunes . Also note that you can pass the slice object to list.__delitem__ , so if you need to do some preprocessing and delegate the actual deletion to the base list, the β€œnaive” del self.l[i] will work correctly.

operator.index will ensure that you get an early exception if your __delitem__ receives an unclassified object that cannot be converted to an index.

+3
source

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

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

Source: https://habr.com/ru/post/1440931/


All Articles