A basic example of coroutines is generators.
Generators can be defined in Python using the yield statement inside a function.
def range_generator(n):
i = 0
while i < n:
print("Generating value {}".format(i))
yield i
i += 1It is also possible to inject (rather than extract) values in the generator through the yield statement.
def parrot():
while True:
message = yield
print("Parrot says: {}".format(message))To insert values in the generator, we can use the send method. In Python world, a generator that can also receive values is called a generator-based coroutine:
generator = parrot()
generator.send(None)
generator.send("Hello")
generator.send("World")
can be advanced only when some resource is ready, therefore eliminating the need for a callback.