How to subclass Python list without type problems?

Firstly, I recommend you follow Björn Pollex’s advice (+1).

To get past this particular problem (type(l2 + l3) == CustomList), you need to implement a custom __add__():

   def __add__(self, rhs):
        return CustomList(list.__add__(self, rhs))

And for extended slicing:

    def __getitem__(self, item):
        result = list.__getitem__(self, item)
        try:
            return CustomList(result)
        except TypeError:
            return result

I also recommend…

pydoc list

…at your command prompt. You’ll see which methods list exposes and this will give you a good indication as to which ones you need to override.

Leave a Comment