Generator - What is the result of a yield expression in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I know that yield turns a function into a generator, but what is the return value of the yield expression itself? For example:

def whizbang(): 
    for i in range(10): 
        x = yield i

What is the value of variable x as this function executes?

http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt

Answers

http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features

>>> def whizbang():
        for i in range(10):
            x = yield i
            print  got sent: , x


>>> i = whizbang()
>>> next(i)
0
>>> next(i)
got sent: None
1
>>> i.send("hi")
got sent: hi
2

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/10695456/what-is-the-result-of-a-yield-expression-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils