[Twisted-Python] iterators/generator

Clark C. Evans cce at clarkevans.com
Wed Mar 12 11:21:04 MST 2003


On Mon, Mar 10, 2003 at 10:19:42AM -0500, Itamar Shtull-Trauring wrote:
| > Hello.  I'd like to write my 'user' level code with generators,
| > and thus, was thinking that new code could perhaps be at least
| > generator friendly... what do you think:
| 
|    def __getitem__(self, index):
|        if index != self.index: raise TypeError, "this is an iterator"
|        self.index += 1
|        if self.hasMoreData:
|           return self.getData()
|        else:
|           raise IndexError

I think that the code below is a fairly good 'first-cut' at supporting
user-level 2.2 generators with code that works in Python 2.1

Anyone object committing the following to python.compat?

Clark

    #
    # This compatibility hack allows for code to be written that 
    # supports 2.2 iterator/generator semantics within Python 2.1
    # This wraps 2.1 lists, mappings, and classes using the __getitem__
    # style iterator to use iter/next
    #
    try:
       StopIteration = StopIteration
       iter = iter
    except:
       # Python 2.1
       StopIteration = IndexError
       class _ListIterator:
           def __init__(self,lst):
               self.idx = 0
               if getattr(lst,'keys',None): lst = lst.keys()
               self.lst = lst
           def next(self):
               idx = self.idx
               self.idx += 1
               return self.lst[idx]
       def iter(lst):
           if hasattr(lst,'__iter__'):
               return lst.__iter__()
           else:
               return _ListIterator(lst)
    
    #
    if __name__ == '__main__:
        def dumpiter(itr):
            next = iter(itr).next
            try:
                while 1: print next()
            except StopIteration: pass
        dumpiter([1,2,3])
        dumpiter({'one': 'value', 'two': 'twoval'})




More information about the Twisted-Python mailing list