简体   繁体   中英

coroutines vs classes in python

My question is a very broad one. Why would one use coroutines when one can use objects? I could easily implement an iterator that works only once under next() and after that you have to call o.send(x). Is there something more to coroutines than state persistence that can be achieved via OOP? Are they lighter? Is it just syntactic sugar? I could actually ask the same about generators vs. iterators but there I think I have read that generators are simply syntactic sugar.

If this is indeed the case, why are coroutines such a big deal? I am sure I am missing something about them but I can't figure out what.

Yes, technically coroutines are syntactic sugar, but not the trivial kind. Any coroutine can potentially be re-written manually without using yield , send , etc. However this transformation may be painful. Consider (adapted from here ):

def print_name(prefix):
  print("Searching prefix: {}".format(prefix))
  while True:
    firstName = (yield)
    lastName = (yield)
    if prefix in firstName or prefix in lastName:
      print("{} {}".format(firstName, lastName))

You could rewrite this as:

class NamePrinter(object):
  def __init__(self, prefix):
    self.prefix = prefix
    self.gotFirstName = False

  def send(self, data):
    if not self.gotFirstName:
      self.firstName = data
      self.gotFirstName = True
    else:
      self.lastName = data
      if self.prefix in self.firstName or self.prefix in self.lastName:
        print(name)
      self.gotFirstName = False

This works. But even with this micro-example, we have to write a lot more when not using coroutines. In more complex stateful coroutines the programmer would manually have to keep track of the current state, which variables are meaningful in the current state, etc.

Coroutines in Python (and similarly async / await in modern JavaScript as well as future C++) automatically transform linear code into a state machine with well-controlled inputs, easy error handling, etc etc.

Coroutines are a way to add asynchonous actions to your application. Objects are just simply things in your application that hold information or do work. So both are used together to create an asynchronous application.

https://www.geeksforgeeks.org/coroutine-in-python/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM