FAQ
In the code snippet below, I have derived a class from the built-in
type "list" to implement 'type checking' for objects placed in the
list and serialization of the list to and from an XML file. I also
want to be able to iterate over the retrieved list using Prev() and
Next(). My question is this: is there a more efficient way to
implement this behavior than the methods below (or some built-in way
to do this)?

Donnal Walter
Arkansas Children's Hospital

=======
class ElementList(list):
def __init__(self):
list.__init__(self)
# ... additional private attributes here
self.__index = 0

def Append(self, object):
"""Append object to the list with 'type checking'."""
# ... implementation code here

def Store(self, writer):
"""Store serialized content to designated xmlWriter."""
# ... implementation code here

def Retrieve(self, reader):
"""Retrieve serialized data from designated xmlReader."""
# ... implementation code here

def Reinit(self):
del self[0:] # empty the list
self.__index = 0

def Prev(self):
"""Return the previous element in the list."""
if self.__index > 1:
self.__index += -1
return self[self.__index - 1]
else: return None

def Next(self):
"""Return the next element in the list."""
if self.__index < len(self):
self.__index += 1
return self[self.__index - 1]
else: return None

Search Discussions

  • Gustavo Cordova at May 6, 2002 at 5:50 pm
    [...snip...]
    Hmmm... strange.

    Simply deriving from a list() will give you iteration through
    the contents for free.

    Or at least, so I thought.

    -gustavo
  • Mike C. Fletcher at May 6, 2002 at 6:26 pm
    Here's a little class from basicproperty that shows using the list
    base-class methods for just about everything while allowing type-checking:

    class rlist( list ):
    """Sub-class of list which calls a method before any addition is allowed"""
    bounds = []
    def __setslice__( self, start, stop, value ):
    """__setslice__ with value checking"""
    value = self.beforeMultipleAdd([ self.beforeAdd(item) for item in value ])
    return list.__setslice__( self, start, stop, value )
    def extend( self, value ):
    """extend with value checking"""
    value = self.beforeMultipleAdd([ self.beforeAdd(item) for item in value ])
    return list.extend( self, value )
    __iadd__ = extend
    def append( self, value ):
    """append with value checking"""
    value = self.beforeAdd( value )
    return list.append( self, value )
    def insert( self, index, value ):
    """insert with value checking"""
    value = self.beforeAdd( value )
    return list.insert( self, index, value )
    def __setitem__( self, index, value ):
    """__setitem__ with value checking"""
    value = self.beforeAdd( value )
    return list.__setitem__( self, index, value )
    def beforeAdd( self, value ):
    """Called before all attempts to add an item"""
    return value
    def beforeMultipleAdd( self, value ):
    """Called before attempts to add more than one item (beforeAdd has already
    been called for each item)"""
    return value


    Now, you get basic for x in mylist operation for free being a list
    sub-class, but if you really want to add Prev and Next mechanisms, you
    would likely do something like this:

    class StepIterator(object):
    def __init__( self, object, startIndex=-1 ):
    self.object = object
    self.index = startIndex
    def Prev( self ):
    self.index = self.index -1
    if self.index < 0:
    raise IndexError( '''Moved beyond beginning of list''')
    return self.object[ self.index ]
    def Next( self ):
    self.index = self.index + 1
    return self.object[ self.index ]

    and use it like this:

    cursor = StepIterator( mylist )
    doSomething(cursor.Next())
    doSomethingElse(cursor.Next())
    yada( cursor.Prev() )

    That's not any more efficient, but it means you can use different
    iterator objects for different purposes simultaneously (though the
    iterators are not individually thread-safe) and your list sub-class
    doesn't keep track of details not relevant to it.

    HTH,
    Mike

    Donnal Walter wrote:
    In the code snippet below, I have derived a class from the built-in
    type "list" to implement 'type checking' for objects placed in the
    list and serialization of the list to and from an XML file. I also
    want to be able to iterate over the retrieved list using Prev() and
    Next(). My question is this: is there a more efficient way to
    implement this behavior than the methods below (or some built-in way
    to do this)?
    ...
    _______________________________________
    Mike C. Fletcher
    http://members.rogers.com/mcfletch/

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMay 6, '02 at 5:19p
activeMay 6, '02 at 6:26p
posts3
users3
websitepython.org

People

Translate

site design / logo © 2022 Grokbase