[Python-Dev] PEP 342 suggestion: start(), __call__() and unwind_call() methods

Nick Coghlan ncoghlan at gmail.com
Sun Oct 9 05:26:15 CEST 2005


James Y Knight wrote:
> 
> On Oct 8, 2005, at 9:10 PM, Nick Coghlan wrote:
> 
>> So, instead of having "return" automatically map to "raise  
>> StopIteration"
>> inside generators, I'd like to suggest we keep it illegal to use  
>> "return"
>> inside a generator
> 
> 
> Only one issue with that: it's _not currently illegal_ to use return  
> inside a generator. From the view of the outsider, it currently  
> effectively does currently map to "raise StopIteration". But not on  the 
> inside, just like you'd expect to happen. The only proposed  change to 
> the semantics is to also allow a value to be provided with  the return.

Huh. I'd have sworn I'd tried that and it didn't work. Maybe I was using a 
value with the return, and had forgotten the details of the error message.

In that case, I have far less of an objection to the idea - particularly since 
it *does* forcibly terminate the generator's block without triggering any 
exception handlers. I was forgetting that the StopIteration exception is 
actually raised external to the generator code block - it's created by the 
surrounding generator object once the code block terminates.

That means the actual change being proposed is smaller than I thought:
   1. Change the compiler to allow an argument to return inside a generator
   2. Change generator objects to use the value returned by their internal 
code block as the argument to the StopIteration exception they create if the 
block terminates

Note that this would change the behaviour of normal generators - they will 
raise "StopIteration(None)", rather than the current "StopIteration()".

I actually kind of like that - it means that generators become even more like 
functions, with their return value being held in ex.args[0].

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list