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

Nick Coghlan ncoghlan at gmail.com
Sun Oct 9 04:43:34 CEST 2005

Guido van Rossum wrote:
> On 10/8/05, Nick Coghlan <ncoghlan at gmail.com> 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, and instead add a new attribute "result" to StopIteration
>>instances such that the following three conditions hold:
>>      # Result is None if there is no argument to StopIteration
>>      try:
>>         raise StopIteration
>>      except StopIteration, ex:
>>         assert ex.result is None
>>      # Result is the argument if there is exactly one argument
>>      try:
>>         raise StopIteration(expr)
>>      except StopIteration, ex:
>>         assert ex.result == ex.args[0]
>>      # Result is the argument tuple if there are multiple arguments
>>      try:
>>         raise StopIteration(expr1, expr2)
>>      except StopIteration, ex:
>>         assert ex.result == ex.args
>>This precisely parallels the behaviour of return statements:
>>   return                 # Call returns None
>>   return expr            # Call returns expr
>>   return expr1, expr2    # Call returns (expr1, expr2)
> This seems a bit overdesigned; I'd expect that the trampoline
> scheduler could easily enough pick the args tuple apart to get the
> same effect without adding another attribute unique to StopIteration.
> I'd like to keep StopIteration really lightweight so it doesn't slow
> down its use in other places.

True. And it would be easy enough for a framework to have a utility function 
that looked like:

   def getresult(ex):
     args = ex.args
     if not args:
         return None
     elif len(args) == 1:
         return args[0]
         return args

Although, if StopIteration.result was a read-only property with the above 
definition, wouldn't that give us the benefit of "one obvious way" to return a 
value from a coroutine without imposing any runtime cost on normal use of 
StopIteration to finish an iterator?


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list