Skip to content

Instantly share code, notes, and snippets.

@pydemo
Last active September 24, 2018 16:25
Show Gist options
  • Select an option

  • Save pydemo/884ff4049af6370c4662fed08058518e to your computer and use it in GitHub Desktop.

Select an option

Save pydemo/884ff4049af6370c4662fed08058518e to your computer and use it in GitHub Desktop.
Co-routine example

Coroutine as a function that can be stopped and resumed.

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 += 1

It 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")

Generator

can be advanced only when some resource is ready, therefore eliminating the need for a callback.

Iterators sound a lot like generators; however, they are more general. In Python, generators are returned by functions that use yield expressions. As we saw, generators support next, therefore, they are a special class of iterators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment