%autosave 10
Autosaving every 10 seconds
(wait for IPython Notebook to get posted)
def f(x):
return x+1, x+2
f(10) == (11, 12)
True
def f(x):
yield x+1
yield x+2
list(f(10)) == [11, 12]
True
Generators require iteration over results.
class Callable(object):
def __call__(self, x):
return x+1, x+2
Callable()(10) == (11, 12)
True
__iter__
, __next__
At the C-level, generators are functions that leave state behind when yielding. It just jumps over the cleanup.
throw
, send
, close
.throw
: throw exception during iteration.close
: halt a generator, clean up state.send
: send value back into a generator.def generator(x):
y = None
y = yield x+1, y
y = yield x+1, y
g = generator(10)
print g.next()
print g.send("abc")
(11, None) (11, 'abc')
izip
, islice
help you manipulate iterables without caring about their contents.chain
just connects iterables, doesn't care.