[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
    try:
       StopIteration = StopIteration
       iter = iter
    except:
       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)
           else:
               return lst
   
2. Then, code within twisted which could possible accept an 
   iterator or generator could be written like this. 

      import python.twisted.util
      try:
           itr = util.iter(getIterator())
           val = itr.next()
           while 1:
              doSomething(val)
              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.

Clark




More information about the Twisted-Python mailing list