How to subclass Python list without type problems?

Possible cut-the-gordian-knot solution: subclass UserList instead of list. (Worked for me.) That is what UserList is there for.


You should probably read these two sections from the documentation:

  • Emulating container types
  • Additional methods for emulating sequence types (Python 2 only)

Edit: In order to handle extended slicing, you should make your __getitem__-method handle slice-objects (see here, a little further down).


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.