Domanda

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'
È stato utile?

Soluzione

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top