slice objects vs. []

Fernando Pérez fperez528 at yahoo.com
Wed May 22 17:12:13 EDT 2002


Quinn Dunkan wrote:

> This seems to imply that [].__getitem__ should accept a slice object.
> Currently I am writing
> 
>     def __getitem__(self, k):
>         if type(k) is type(slice(0)):
>             return self.data[k.start:k.end]
>         else:
>             return self.data[k]
> 
> ... which is awkward, in addition to losing k.step.
> 
> BTW, is there any particular reason slice() is not a type?  I expected to be
> able to write 'isinstance(k, slice)'.
> 

The docs are a bit outdated, I think. They don't describe __getslice__, which 
is what you want. Her's an example from my code:


import UserList # don't subclass list so this works with Python2.1

class InputList(UserList.UserList):
    """Class to store user input.

    It's basically a list, but slices return a string instead of a list, thus
    allowing things like (assuming 'In' is an instance):
    
    exec In[4:7]

    or

    exec In[5:9] + In[14] + In[21:25]"""
    
    def __getslice__(self,i,j):
        return ''.join(UserList.UserList.__getslice__(self,i,j))


hth,

f



More information about the Python-list mailing list