[Python-Dev] Possible resolution of generator expression variablecapture dilemma

Anders J. Munch andersjm at dancontrol.dk
Wed Mar 24 04:02:56 EST 2004


From: "Greg Ewing" <greg at cosc.canterbury.ac.nz>
>
>What's different is that Scheme's equivalent of a
> for-loop creates a new binding for the loop variable on each
> iteration. This tends to result in fewer late-binding surprises,
> because you get the effect of variable capture -- but due to the
> semantics of the for-loop, and other common constructs which introduce
> new bindings, rather than anything that goes on inside them.

I had a similar thought - to early-bind loop variables and late-bind
everything else, for exactly the reason you give.

Alas it doesn't do the job because it fails to handle loop-local
derivatives.  A simple change to Tim's example:

     pipe = source
     for p in predicates:
         filter = p.filter
         # add a filter over the current pipe, and call that the new pipe
         pipe = e for e in pipe if filter(e)

Now we can do something clever to fix p, but then we really should do
the same thing for filter.  But how can the interpreter know that
filter is a loop-local derivative of the loop variable?  That would
require an uncomfortable amount of dwim/magic.

- Anders





More information about the Python-Dev mailing list