[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Terry Reedy tjreedy at udel.edu
Sat Oct 4 16:04:36 CEST 2008

Greg Ewing wrote:
> Arnaud Delobelle wrote:
>> Isn't this better as:
>>     buttons.append(Button(title, getattr(game, action)))
>> Unless you want late binding of 'game',
> Well, you might, for example if you implement restoring a
> saved game by unpickling a Game object and assigning it
> to game.

To me, this example and comment proves my point.  If you want 'action' 
interpolated immediately, to not actually be a variable of each 
function, while you want 'game' left to be a true free variable, then 
overtly say so specifically in one way or another without magic.

In my opinion, the 'evil default arg hack' does this nicely (though not 
completely), especially if a new name is used for the lambda local.
      lambda a=action: getattr(game,a)
This is only 4 extra keystrokes.  If the function is left anonymous and 
only called by clicking a button, there is no danger of a 'user' 
accidentally calling the function with an extra arg that overrides the 
default.  This fact to me eliminates the main objection to the usage.

If one still does not like that for whatever reason, complete value 
interpolation is nicely done by
    eval("lambda: getattr(game,%s)" % action)
That is 13 extra spaces, including 2 spaces for easier reading.

> There's always some way to rearrange it so that it works,

Also my point.

> but the point is that it's easy to write things like this
> that don't work, unless you really keep your wits about
> you.

It is also easy to write things that don't work, unless you really keep 
your wits about you, with lists and other mutables, and with floats ;-).

Terry Jan Reedy

More information about the Python-ideas mailing list