[Python-Dev] code blocks using 'for' loops and generators

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Mar 15 00:02:41 CET 2005


Josiah Carlson wrote:

> Since PEP 310 was already mentioned, can we just say that the discussion
> can be boiled down to different ways of spelling __enter__/__exit__ from
> PEP 310?

It's not quite the same thing. PEP 310 suggests a mechanism
with a fixed control flow -- do something on entry, do the
code block, do something on exit. A general block-passing
mechanism would give complete control to the function as
to when and how to call the block.

However, it's possible that if generators were enhanced
with some means of allowing yield inside try-finally,
then generators plus PEP 310 would cover most use cases:
for-loops and generators when you want to loop, and
PEP 310 when you don't.

So rather than coming up with new syntax at this point,
perhaps it would be better to concentrate on the problem
of yield inside try-finally. Even if the finally can't
be guaranteed to run under all conditions, I think it
would be useful if it could be arranged so that

   for x in somegenerator():
     ...
     raise Blather
     ...

would caused any finallies that the generator was suspended
inside to be executed. Then the semantics would be the
same as if the for-loop-over-generator were implemented by
passing a thunk to a function that calls it repeatedly.

-- 
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