Generator and return value

Frank Millman frank at chagford.com
Wed Jun 7 03:37:51 EDT 2017


"Jussi Piitulainen"  wrote:

> Frank Millman writes:
> 
> > It would be nice to write a generator in such a way that, in addition
> > to 'yielding' each value, it performs some additional work and then
> > 'returns' a final result at the end.
> >
> > From Python 3.3, anything 'returned' becomes the value of the
> > StopIteration 
> > exception, so it is possible, but not pretty.
> >
> > Instead of -
> >    my_gen = generator()
> >    for item in my_gen():
> >        do_something(item)
> >    [how to get the final result?]
> >
> > you can write -
> >    my_gen = generator()
> >    while True:
> >        try:
> >            item = next(my_gen())
> >            do_something(item)
> >        except StopIteration as e:
> >            final_result = e.value
> >            break
> >
> > Is this the best way to achieve it, or is there a nicer alternative?
> 
> Like this, and imagination is the limit:
> 
> def generator(box):
>     yield 1
>     box.append('won')
>     yield 2
>     box.append('too')
>     yield 3
>     box.append('tree')
> 
> mabox = []
> for item in generator(mabox): pass
> print(*mabox)
> # prints: won too tree
> 

That is neat. Thanks

Frank





More information about the Python-list mailing list