I've used Python for many years but only gradually studied the more obscure features of the language, as most of my code is for data processing. Generators based on yield
are part of my routine toolkit, and recently I read about coroutines. I found an example similar to this:
def averager():
sum = 0.0
n = 0
while True:
value = yield
sum += value
n += 1
print(sum/n)
avg = averager()
next(avg) # prime the coroutine
avg.send(3)
avg.send(4)
avg.send(5)
which prints the average of the values sent to it. I figured something like this might come in useful in data processing pipelines so I resolved to keep it in the back of my head. That is, until I read the following notice in the Python documentation:
Support for generator-based coroutines is deprecated and is scheduled for removal in Python 3.10.
Obviously I'd like to write future-proof code so at this point it's probably useless to start learning generator-based coroutines. My question, then, is: How to implement this example using the native (asyncio
) coroutines? I have a much harder time wrapping my head around the native coroutine syntax.
While trying to search for an answer, I found a related question which has a comment and an answer that are basically saying "you can't do it with async
, do it with yield
-based coroutines instead". But if those are going away, is there going to be any way to do this with coroutines in 3.10+?