python yield and stopiteration in one loop?

Viewed 40942

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,

3 Answers

I come from the future. I recommend yield from:

def gen(q, header="header", footer="footer"):
    yield header
    yield from q
    yield footer

Output:

>>> g = gen([1, 2, 3, 4])
>>> print(*g, sep="\n")
header
1
2
3
4
footer
Related