[Python-Dev] PEP 289 - Generator Expressions - Let's Move Forward

Samuele Pedroni pedronis at bluewin.ch
Wed May 5 20:59:40 EDT 2004


At 11:26 23.04.2004 -0700, Guido van Rossum wrote:

>My reasons for (still!) preferring late binding are:
>
>(a) I find it hard to defend automatic variable capture given Python's
>     general late-binding semantics

I have been thinking about reason (a), the point is that a genexp is not 
simply a new way to introduce a closure, it is not simply sugar over lambda 
or def. A genexp is sugar for defining on the fly a generator closure and 
second instatiating it! Now there are two parts to that, it is true that 
closures in Python have late-bindings semantics but when they are deployed 
people in most cases use idioms that circuvent and neutralize late-bindings.

def make_show_action(msg):
    def action(evt,msg):
        show(msg)
    return action

used as

for act,msg in msgs:
   pnl.add(Button(act,action=make_show_action(msg))

or

for act,msg in msgs:
   pnl.add(Button(act,lambda msg=msg: show(msg)))

in fact here lambda has late-bindings semantics and we eschew them by not 
having any free variable at all.

Of course here enters (b), mixing for and genexp is advanced use. That's 
really a gut-feelings call at this point.

For most practical cases, for closures, late-bindings sematics seems 
something to keep under control, it's an implementation detail to allow 
recursive and mutally recursive nested functions.

So to repeat genexp have no simple direct correspondence to a lambda or a 
def. They are sugar for some more involved code, so I think it is more a 
call of what is the general idiomatic form for that kind of code, also 
maybe considering that the genexp is hiding the details of what is really 
going on (kind of supplying sheep's clothes to a wolf).

Maybe the sane thing is late-bindings, maybe early. But I don't think that 
as suggested by (a) that there is some deep design logic internal to Python 
at stake here.

At most the argument could be that late-bindings make things easier to 
explain because they are kind of like lambdas. Maybe, maybe not. Then there 
is (b).

>(b) I believe that use cases needing early binding are uncommon and
>     strained: they all involve creating a list of generator
>     expressions, which IMO is a pretty unusual thing to do

regards




More information about the Python-Dev mailing list