[EMAIL PROTECTED] wrote: > Hi all, > > 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 :) > In your recursive call you are passing a single argument, a tuple. You should create it to multiple arguments with a star. Neither do you do anything with the iterator after you create it.
Try (untested) #################################### def getNextScalar(*args): for arg in args: if ( isinstance(arg, tuple)): for a in getNextScalar(*arg): yield a else: yield arg #################################### regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list