To understand how asynchronous programming works in Python, it is important to first understand how iterators and generators work because they are the basis of asynchronous features in Python.
An iterator in Python is a class that implements the Iterator protocol. The class must implement the following two methods:
__iter__()
: ; ;Returns the actual iterator. It often returnsself
next()
: ;Returns the next value untilStopIteration()
is raised
In the following example, we'll implement the Fibonacci sequence as an iterator:
class Fibo: def __init__(self, max=10): self.a, self.b = 0, 1 self.max = max self.count = 0 def __iter__(self): return self def next(self): try: return self.a finally: if self.count == self.max: raise StopIteration() self.a, self.b = self.b, self.a + self.b ...