Generator and return value

Ian Kelly ian.g.kelly at gmail.com
Wed Jun 7 13:58:09 EDT 2017


On Wed, Jun 7, 2017 at 10:00 AM, Rob Gaddi
<rgaddi at highlandtechnology.invalid> wrote:
>
> On 06/06/2017 11:13 PM, Frank Millman wrote:
>>
>> Hi all
>>
>> 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
>>
>> Is this the best way to achieve it, or is there a nicer alternative?
>>
>> Thanks
>>
>> Frank Millman
>
> class MyGeneration:
>   def __iter__(self):
>     yield from ('people', 'try', 'to', 'put', 'us', 'down')
>     self.final = 'talking about'
>
> mygen = MyGeneration()
> for item in mygen:
>   print(item)
> print(mygen.final)


Or as a generic wrapper:

class CaptureValue:
  def __init__(self, iterable):
    self._iter = iter(iterable)

  def __iter__(self):
    return self

  def __next__(self):
    try:
      return next(self._iter)
    except StopIteration as e:
      self.value = e.value
      raise

capture = CaptureValue(generator())
print(list(capture))
print(capture.value)



More information about the Python-list mailing list