Working with __getitem__(), __setitem__(), __delitem__(), and slices

The StatsList2 example didn't show us the implementation of __setitem__() or __delitem__() because they involve slices. We'll need to look at the implementation of a slice before we can implement these methods properly.

Sequences have two different kinds of indexes:

  • a[i]. This is a simple integer index.
  • a[i:j] or a[i:j:k]: These are slice expressions with start:stop:step values. Slice expressions can be quite complex, with seven different variations for different kinds of defaults.

This basic syntax works in three contexts:

  • In an expression, relying on __getitem__() to get a value
  • On the left-hand side of assignment, relying on __setitem__() to set a value
  • On a del statement, relying on __delitem__() to delete a value

When we do something like seq[:-1], we write a slice expression. The underlying __getitem__() method will be given a slice object, instead of a simple integer.

The reference manual tells us a few things about slices. A slice object will have three attributes: start, stop, and step. It will also have a method function called indices(), which will properly compute any omitted attribute values for a slice.

We can explore the slice objects with a trivial class that extends list:

class Explore(list): 
    def __getitem__( self, index ): 
        print( index, index.indices(len(self)) ) 
        return super().__getitem__( index ) 

This class will dump the slice object and the value of the indices() function result. Then, use the superclass implementation, so that the list behaves normally otherwise.

Given this class, we can try different slice expressions to see what we get:

>>> x = Explore('abcdefg') 
>>> x[:] 
slice(None, None, None) (0, 7, 1) 
['a', 'b', 'c', 'd', 'e', 'f', 'g'] 
>>> x[:-1] 
slice(None, -1, None) (0, 6, 1) 
['a', 'b', 'c', 'd', 'e', 'f'] 
>>> x[1:] 
slice(1, None, None) (1, 7, 1) 
['b', 'c', 'd', 'e', 'f', 'g'] 
>>> x[::2] 
slice(None, None, 2) (0, 7, 2) 
['a', 'c', 'e', 'g'] 

In the preceding slice expressions, we can see that a slice object has three attributes, and the values for those attributes come directly from the Python syntax. When we provide the proper length to the indices() function, it returns a three-tuple value with start, stop, and step values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset