[Python-Dev] PEP 343 - New kind of yield statement?

Greg Ewing greg.ewing at canterbury.ac.nz
Thu May 19 06:44:49 CEST 2005


Michael Hudson wrote:

> This is, to me, neat and clear.  I don't find the idea that iterators
> are tied to exactly 1 for loop an improvement (even though they
> usually will be).

To fix this in a fully backward-compatible way, we
need some way of distinguishing generators that
expect to be finalized.

Suppose we leave the 'yield' statement alone, and
introduce a new statement 'suspend', which alone
has the new capabilities of

(1) allowing injection of exceptions
(2) ability to return a value
(3) permissibility in a try-finally

Doing throw() on a generator that is stopped at
a yield statement would simply raise the exception
without changing the state of the generator. So
the for-loop could be made to finalize by default,
and existing generators would be unaffected.

A with-statement generator would then look like

   @with_template
   def foo():
     initialize()
     try:
       suspend
     finally:
       finalize()

which I think looks quite nice, because 'suspend'
seems more suggestive of what is happening when
you're not yielding a value. The same thing applies
to coroutine-type applications.

For partial iteration of new-style generators,
there could be a new statement

   for var from expr:
     ...

or maybe just a wrapper function

   for var in partial(expr):
     ...

-- 
Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+


More information about the Python-Dev mailing list