[Twisted-Python] deferred generators in inline callbacks

Алексей Кирпичников alex.kirp at gmail.com
Tue Dec 20 13:24:24 EST 2011


Hi.

I have a question about inline callbacks usage.

Let's assume I have an iterator that works synchronously. I want to
wrap this generator to work asynchronously in threads:

def some_generator():
    cursor = make_iterator() # cursor's 'next' method uses some nasty
blocking I/O
    while 1:
        yield deferToThread(cursor.next)


Next, I want to asynchronously iterate over this generator in
inlineCallbacks semantics. I should say:

@inlineCallbacks
def do_stuff():
    for item in some_generator():
        try:
            real_item = yield item
            # do stuff with real_item
        except StopIteration:
            break


It somewhat annoys me that I should always convert item to real_item
so inlineCallbacks can properly asynchronize my code. I also need to
implement StopIteration myself :(
Is there any easier way to do this in Twisted?

Thanks in advance!

-- 
Alex



More information about the Twisted-Python mailing list