iterating over a derived list
Mike C. Fletcher
mcfletch at rogers.com
Mon May 6 14:26:07 EDT 2002
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/
More information about the Python-list
mailing list