generator functions: why won't this work?
Mel
mwilson at the-wire.com
Tue Apr 1 23:11:46 EDT 2008
zillow20 at googlemail.com wrote:
> I'm trying to understand generator functions and the yield keyword.
> I'd like to understand why the following code isn't supposed to work.
> (What I would have expected it to do is, for a variable number of
> arguments composed of numbers, tuples of numbers, tuples of tuples,
> etc., the function would give me the next number "in sequence")
> ####################################
> def getNextScalar(*args):
> for arg in args:
> if ( isinstance(arg, tuple)):
> getNextScalar(arg)
> else:
> yield arg
> ####################################
>
> # here's an example that uses this function:
> # creating a generator object:
> g = getNextScalar(1, 2, (3,4))
> g.next() # OK: returns 1
> g.next() # OK: returns 2
> g.next() # not OK: throws StopIteration error
>
> ####################################
>
> I'm sure I'm making some unwarranted assumption somewhere, but I
> haven't been able to figure it out yet (just started learning Python a
> couple of days ago).
>
> Any help will be appreciated :)
`getNextScalar(arg)` doesn't yield anything (it creates, but doesn't
use, a new generator object,) so nothing comes out. Look at
>>> h = getNextScalar(1,2,(3,4),5)
>>> h.next()
1
>>> h.next()
2
>>> h.next()
5
Maybe you want
if isinstance (arg, tuple):
for s in getNextScalar (*arg):
yield s
Mel.
More information about the Python-list
mailing list