7
Generators and Coroutines – Infinity, One Step at a Time
Generator functions are functions that behave like iterators by generating the return values one by one. While traditional methods build and return a list
or tuple
of items with a fixed length, a generator will yield
a single value only when requested by the caller. The side effect is that these generators can be infinitely large because you can keep yielding forever.
In addition to generators, there is a variation to the generator’s syntax that creates coroutines. Coroutines are functions that allow multitasking without requiring multiple threads or processes. Whereas generators can only yield values to the caller based on the initial arguments, coroutines enable two-way communication ...
Get Mastering Python - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.