Python generators - float ((yield))?

I am reading the following tutorial about generators in Python http://excess.org/article/2013/02/itergen2/

It contains the following code:

def running_avg(): "coroutine that accepts numbers and yields their running average" total = float((yield)) count = 1 while True: i = yield total / count count += 1 total += i 

I do not understand the meaning of float((yield)) . I thought that yield used to "return" a value from a generator. Is this another use of yield ?

+4
source share
2 answers

Yes, yield can also be obtained by sending to the generator:

 >>> avg_gen = running_avg() >>> next(avg_gen) # prime the generator >>> avg_gen.send(1.0) 1.0 >>> print avg_gen.send(2.0) 1.5 

Any value passed to the generator.send() method is returned by the yield expression. See yield documentation.

yield an expression was made in Python 2.5; before it was just a statement and only produced values ​​for the generator. By making the yield expression and adding .send() (and other methods to throw exceptions), you can now use simple coroutines ; see PEP 342 for initial motives for this change.

+2
source

Its extended yield syntax for coroutines

Read this: http://www.python.org/dev/peps/pep-0342/

+3
source

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


All Articles