简体   繁体   中英

Python Generator Behavior

What am I misunderstanding about generators, that I'm not getting the output I'm expecting? I'm trying to create a simple function that will output whatever data i .send() it, or return 'none' if no information is sent.

import pudb
#pudb.set_trace()
def gen():
        i = 0
        while True:
                val = (yield i)
                i = val
                if val is not None:
                        yield val
                else:
                        yield 'none'

test = gen()
next(test)
print test.send('this')
print test.send('that')
print test.next()
print test.send('now')

Expected output:

'this'
'that'
'none'
'now'

Actual output:

'this'
'this'
'none'
'none'

You yield each value twice. Once here:

val = (yield i)

and once here:

yield val

You should only yield each value once, and capture the user's input, like so:

def parrot():
    val = None
    while True:
        val = yield val

If you really want to yield the string 'none' instead of the actual None object when the user calls next , you can do that, but it may be a bad idea:

def parrot():
    val = None
    while True:
        val = yield ('none' if val is None else val)

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