Welcome, guest | Sign In | My Account | Store | Cart

As subclassing list has a problem when using __getitem__, __delitem__ and __setitem__ methods with slices (they don't get called because parent implements __getslice__, __delslice__ and __setslice__ respectively), I've coded this UserList class that is a subclass of list, but overwrites these methods. By subclassing this class, you can overwrite __getitem__ and it will be called correctly for slices.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class UserListSubclass(list):
    def __getslice__(self, i, j):
        return self.__getitem__(slice(i, j))
    def __setslice__(self, i, j, seq):
        return self.__setitem__(slice(i, j), seq)
    def __delslice__(self, i, j):
        return self.__delitem__(slice(i, j))

# Subclass this class if you need to overwrite __getitem__ and have it called
# when accessing slices.
# If you subclass list directly, __getitem__ won't get called when accessing
# slices as in mylist[2:4].
Created by nosklo on Mon, 18 Aug 2008 (MIT)
Python recipes (4591)
nosklo's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks