[Twisted-Python] asynchronous python generator

Jean Daniel jeandaniel.browne at gmail.com
Mon Jul 12 12:43:55 EDT 2010


I wrote a small client protocol which connects to a notification
server. The client role is to connect, and then to print the
notification which comes from the server until the server says "stop"
(a netcat server do just fine, I use "nc -C -l 6789"). I would like
the API for this client protocol to be compatible with the "for"
python loop. Here is the client

class Notif(basic.LineReceiver):

    def lineReceived(self, data):

    def __iter__(self):
        return self

    def next(self):
        self.d = defer.Deferred()
        notif = yield self.d
        if notif=="stop":

Here is an example of how to use this client:

def gotConnection(conn):

    for notif in conn:
        print notif


c = protocol.ClientCreator(reactor, Notif)
c.connectTCP("localhost", 6789).addCallback(gotConnection)

Except that is does not work: I think that the next() method of the
generator is indeed automatically called by the "for" machinery but
its return value is not yielded as the inlineCallbacks requires it.
This works for instance, and it is very close to a for loop:

def gotConnection(conn):

    while True:
            print (yield conn.next())
        except StopIteration:

Does someone knows how to make the for loop work with data coming from
network requests?

More information about the Twisted-Python mailing list