Coroutines in Python: best practices

I am wondering what is best for writing coroutines in Python 3. I develop basic methods that should accept some input (using the .send () method), perform calculations on this input, and then output the output.

The first approach I found is to do the following:

def coroutine(func):
  data = yield
  while 1:
    data = yield func(data)

It seems to work, but the line in the loop bends my mind. It looks like it first gives a function, and then takes input and executes the assignment after resuming. This is completely unintuitive for me.

Another approach that I am considering is:

def coroutine():
  while 1:
    data = yield
    [ do stuff with data here ... ]
    yield result

, , . . (, "gen.send(2)" ) "gen.send(None)", .

, "yield", : return .

, , , , , , , . ?


: . "g.send(None)" .

+4
1

, . " " . :

def coroutine():
  data = yield
  while True:
    print("I am doing stuff with data now")
    data = data * 2
    data = yield data

:

>>> co = coroutine()
>>> next(co)
>>> co.send(1)
I am doing stuff with data now
2
>>> co.send(88)
I am doing stuff with data now
176

, yield , , , send. (, send , send , .) : yield, out, yield , sent.

"", "", , . , (, ). , send , ( yield). , yield, "" , , "" .

, , . , , , , API , . , / send yield. , (, , , , , ).

+8

Source: https://habr.com/ru/post/1618665/


All Articles