[Python-ideas] Possible PEP 380 tweak

Guido van Rossum guido at python.org
Tue Oct 26 19:01:50 CEST 2010

On Tue, Oct 26, 2010 at 5:22 AM, Jacob Holm <jh at improva.dk> wrote:
>>> Here's a stupid idea... let g.close take an optional argument that it
>>> can return if the generator is already exhausted and let it return the
>>> value from the StopIteration otherwise.
>>> def close(self, default=None):
>>>    if self.gi_frame is None:
>>>        return default
>>>    try:
>>>        self.throw(GeneratorExit)
>>>    except StopIteration as e:
>>>        return e.args[0]
>>>    except GeneratorExit:
>>>        return None
>>>    else:
>>>        raise RuntimeError('generator ignored GeneratorExit')
>> You'll have to explain why None isn't sufficient.

> It is not really necessary, but seemed "cleaner" somehow.  Think of
> "g.close(default)" as "get me the result if possible, and this default
> otherwise".  Then think of dict.get()...

Hm, I'd say there always is a result -- it just sometimes is None. I
really don't want to make distinctions between falling off the end of
the function, "return" without a value, "return None", "raise
StopIteration()", "raise StopIteration(None)", or even (in response to
a close() request) "raise GeneratorExit".

> You mentioned some possible extensions though.  At a guess, at least
> some of these would benefit greatly from the use of generators.  Maybe
> such an extension would be a better example?

Yes, see the avg() example I posted in the parent thread.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list