2

I understand Python coroutines are generators functions that consume data. What are they useful? Can you give me some use cases?

Below is a coroutines example.

def match(pattern):
    print('Looking for ' + pattern)
    try:
        while True:
            s = (yield)
            print ("S is: {}".format(s))
            if pattern in s:
                print(s)
    except GeneratorExit:
        print("=== Done ===")


def read(text, next_coroutine):
    for line in text.split():
        next_coroutine.send(line)
    next_coroutine.close()



text = 'Commending spending is offending to people pending lending!'
matcher = match('ending')
matcher.__next__()
read(text, matcher)
user1187968
  • 7,154
  • 16
  • 81
  • 152
  • 1
    Asking for "some use cases" or "some examples" brings this out of the sweet spot of a narrow question with a canonical answer -- a question asking for examples can never have an answer that's canonical and complete, because more examples can always exist. – Charles Duffy Jun 13 '18 at 19:40
  • 1
    [knock yourself out](https://www.youtube.com/watch?v=Z_OAlIhXziw) – timgeb Jun 13 '18 at 19:40
  • that said, one of the attributes that makes a coroutine a better tool for a job than a typical one-off function is a need for persistent state between invocations. That can just be as simple as a buffer of content received in the last call that couldn't be processed yet because the records weren't complete, to pick one common example. – Charles Duffy Jun 13 '18 at 19:41
  • That said, we **do** have duplicates for this already (site rules change over time, but we don't usually remove questions if they were valid when asked); ie. [What are the use cases for a coroutine?](https://stackoverflow.com/questions/303760/what-are-use-cases-for-a-coroutine); [Why do we need coroutines in Python?](https://stackoverflow.com/questions/40925797/why-do-we-need-coroutines-in-python); [What are things you have to use coroutines over functions for in Python?](https://stackoverflow.com/questions/32238949/what-are-the-things-you-have-to-use-coroutines-over-functions-in-python) – Charles Duffy Jun 13 '18 at 19:42

0 Answers0