Overriding append method after inheriting from a Python List

Viewed 35709

I want to create a list that can only accept certain types. As such, I'm trying to inherit from a list in Python, and overriding the append() method like so:

class TypedList(list):
    def __init__(self, type):
        self.type = type

    def append(item)
        if not isinstance(item, type):
            raise TypeError, 'item is not of type %s' % type
        self.append(item)  #append the item to itself (the list)

This will of cause an infinite loop because the body of append() calls itself, but I'm not sure what to do other than using self.append(item).

How I should go about doing this?

6 Answers
Related