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

Samuele Pedroni pedronis at strakt.com
Tue Mar 15 01:36:57 CET 2005

Brian Sabbey wrote:
>> 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.
> One difficulty is that one can never know if the user intends to
> still use the generator, like so:
> a = somegenerator() try: for x in a: raise Blather except: a.next()
> I think they only way you can really be sure .next() will not be
> called again is if the generator is no longer referenced.  Someone
> submitted a patch once to execute "finallies" when the generator is
> __del__eted, but it was rejected for various reasons.
> In my original post in this thread I tried to provide a mechanism
> such as you describe by providing __call__ as an alternative to
> 'next', but now I am convinced that it is better to introduce a new
> syntax instead of re-using generators.
> Incidentally, passing the thunk "behind the scenes" as the first 
> argument (as mentioned previously) allows one to avoid using lambda
> to do things such as sort (I hear lambdas are on the way out), while
>  remaining anonymous:
> with x, y from a.sort(): value cmp(x.k1, y.k1) or (x.k2, y.k2)
> (or whatever the preferred syntax is) instead of:
> a.sort(lambda x,y : cmp(x.k1, y.k1) or (x.k2, y.k2))
> Not that I find either form better than the other, but I do find both
>  better than have to define a named function.

Notice that syntax is the key issue here, it is not like it is hard to
think a range of semantics for thunks/anonymous functions. In fact 
thunks can probably be just closures with some tweaks up to the yield issue.

In fact if some unnatural (for Python POV likely) parentheses would be
acceptable but they are very likely not, it is simple to devise
syntaxes that allows anonymous functions pretty much everywhere. This
would allow for some rather unwieldy code.

OTOH a suite-based syntax for thunks can likely not work as a substitute 
of lambda for cases like:

f(lambda: ..., ...)

where the function is the first argument, and then there are further 
arguments. (Of course not-so-natural helper functions can be written
to swap arguments around).

Apart this one very hard problem, it would be nice to be able to define
and pass more thunks simultaneously. In particular a more concise syntax for

   def setx(self, v): self._x = v
   def getx(self): return self._x
   x = property(getx,setx)

was considered in the past discussions about the topic a worthy goal.


More information about the Python-Dev mailing list