Mini-Reference

Generator definition:

def generator(args):
    ...
    yield something
    yield from something_else
    ...
    return result

Generator instance operations:

g = generator(args)
next(g)
g.send(value)
g.close()
g.throw(exc, val, tb)
result = yield from gen

In [1]:
def gen():
    message = 'Hello'
    while True:
        print('gen: ready to yield %r' % message)
        item = yield message
        print('gen: got %r' % item)
        message = 'message for %s' % item

In [2]:
g = gen()
g


Out[2]:
<generator object gen at 0xb4b6c2ac>

In [3]:
a = next(g)
a


gen: ready to yield 'Hello'
Out[3]:
'Hello'

In [4]:
a = g.send('one')
a


gen: got 'one'
gen: ready to yield 'message for one'
Out[4]:
'message for one'

In [5]:
a = g.send('two')
a


gen: got 'two'
gen: ready to yield 'message for two'
Out[5]:
'message for two'