pythonlistsubclassing

Emulating the list.insert() method as a subclass of Python's list


I'm trying to build a class that inherits methods from Python's list, but also does some additional things on top... it's probably easier just to show code at this point...

class Host(object):
    """Emulate a virtual host attached to a physical interface"""
    def __init__(self):
    # Insert class properties here...
    pass

class HostList(list):
    """A container for managing lists of hosts"""
    def __init__(self):
        self = []

    def append(self, hostobj): 
        """append to the list...""" 
        if hostobj.__class__.__name__ == 'Host': 
            self.insert(len(self), hostobj)
        else:
            _classname = hostobj.__class__.__name__
            raise RuntimeError, "Cannot append a '%s' object to a HostList" % _classname

My problem is this... if I want to perform the same kind of object admission tests on insert() as I did on append(), I can't find a way to code the new methods without to sacrificing support for one list expansion method (i.e. list.append(), list.insert(), or list.extend()). If I try to support them all, I wind up with recursive loops. What is the best way around this problem?

Edit... please find my final answer, based on Nick's recommendation below...


Solution

  • If you can possibly avoid it, don't inherit from builtin classes. (You can, but that doesn't mean you should without a really compelling reason)

    Those classes are optimised for speed, and that makes inheriting from them correctly quite tedious, since you end up having to override almost everything.

    Inheriting from collections.MutableSequence instead lets you implement just a few essential methods, and get a robust fully featured implementation of the sequence API, without all the quirks and caveats that come with inheriting from list.