简体   繁体   中英

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 don't understand the meaning of float((yield)) . I thought yield was used to "return" a value from a generator. Is this a different use of yield ?

Its an extended yield syntax for coroutines

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

Yes, yield can also recieve , 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 the yield expressions documentation.

yield was made an expression in Python 2.5; before it was just a statement and only produced values for the generator. By making yield an expression and adding .send() (and other methods to send exceptions as well) generators are now usable as simple coroutines ; see PEP 342 for the initial motivations for this change.

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