Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python yield and stopiteration in one loop?

Tags:

i have a generator where i would like to add an initial and final value to the actual content, it's something like this:

# any generic queue where i would like to get something from q = Queue()  def gen( header='something', footer='anything' ):     # initial value header     yield header      for c in count():         # get from the queue         i = q.get()         # if we don't have any more data from the queue, spit out the footer and stop         if i == None:             yield footer             raise StopIteration         else:             yield i 

Of course, the above code doesn't work - my problem is that i would like it such that when there's nothing left in the queue, i want the generator to spit out the footer AND raise the StopIterator. any ideas?

Cheers,

like image 776
yee379 Avatar asked Jul 22 '11 02:07

yee379


People also ask

Can you yield and return in the same function Python?

It's allowed in Python 3. x, but is primarily meant to be used with coroutines - you make asynchronous calls to other coroutines using yield coroutine() (or yield from coroutine() , depending on the asynchronous framework you're using), and return whatever you want to return from the coroutine using return value .

Does yield raise StopIteration?

A yield point is reached, and the yielded value is returned. The frame is returned from; StopIteration is raised.

Can I use yield with the for loop Python?

yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.

Does yield stop the function Python?

Difference between return and yield Python The main difference between them is, the return statement terminates the execution of the function. Whereas, the yield statement only pauses the execution of the function.


1 Answers

You seem to be overcomplicating this quite a bit:

>>> q = [1, 2, 3, 4] >>> def gen(header='something', footer='anything'):         yield header         for thing in q:             yield thing         yield footer   >>> for tmp in gen():         print(tmp)   something 1 2 3 4 anything 

StopIteration will automatically be raised when a generator stops yielding. It's part of the protocol of how generators work. Unless you're doing something very complex, you don't need to (and shouldn't) deal with StopIteration at all. Just yield each value you want to return from the generator in turn, then let the function return.

like image 192
Ben Avatar answered Nov 03 '22 05:11

Ben