[Twisted-Python] iterators/generator

Clark C. Evans cce at clarkevans.com
Mon Mar 10 01:34:29 EST 2003

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:

1.  We add the following code fragment somewhere in a python.util
    or equivalent:

    # primative support iterators for 2.1
       StopIteration = StopIteration
       iter = iter
       class StopIteration(Exception): pass
       class _ListIterator:
           def __init__(self,lst):
               self.lst = list(lst)
           def next()
               if self.lst: return self.lst.pop(0)
               else: raise StopIteration
       def iter(lst):
           if type(lst) == type([]) or type(lst) == type(tuple()):
               return _ListIterator(lst)
               return lst
2. Then, code within twisted which could possible accept an 
   iterator or generator could be written like this. 

      import python.twisted.util
           itr = util.iter(getIterator())
           val = itr.next()
           while 1:
              val = itr.next()
      except util.StopIteration: pass

Just thoughts... using generators from 'user' land is really
very useful, and it'd be nice if lower levels of Twisted allowed
for this by a mechanism similar to the above.


More information about the Twisted-Python mailing list