Something is rotten in Denmark...

Terry Reedy tjreedy at udel.edu
Thu Jun 2 02:02:23 EDT 2011


On 6/1/2011 8:40 PM, harrismh777 wrote:

> The part that I don't see much about in the docs (some books, that is)
> is that the lambda lookups occur late (the lambda is evaluated at the
> time it is called). The Python docs on-line *do say* this (I found too
> late) but its one quick phrase that can be missed. So, the i in
> range(10) is sitting there at '9' by the time *any* of the ten lambdas
> get called. This is not intuitive, nor good. IMHO

I readily admit that the docs might be improved. Part of the reason I 
spend time responding to issues like this is to practive giving 
explanations that I might use in my own writings or even in the doc. I 
have at least one small idea already.

> Yes, I can explicitly grab each 'i' as it flies by with a little clever
> coding of the default value for the lambda n, i=i: i + n but that
> 'trick' is not intuitive, nor is it clear reading. It 'works' is just
> about all one can say for it (not very elegant).

You found the alternative of using a closure (the g(i) that returns a 
*new* function for each i). You happened to use lambda to create each 
new function; a nested def statement would have served just as well. 
Replacing the default arg trick was one of the reasons to introduce 
closures (in about 2.3). It might be considered the recommended solution 
to this use case.

> work. I'm wondering if whether it would make some sense to put some
> 'binding smarts' into the interpreter to allow for 'interpreter
> intuition' (say AI ) that would presume to understand when early vs late
> binding makes sense and apply early binding in those cases where the
> context is not ambiguous and when it is clear that an iterable is being
> passed to the constant lambda function?

Oh the irony of this proposal. You scolded us for breaking code with 2 
to 3 changes, and here you propose a change more radical than anything 
done in Python 3, and certain to break code, introduce bugs, complicate 
the language, and reduce its functionality. Most of Guido's design 
decision are rejections of such changes ;-).

-- 
Terry Jan Reedy




More information about the Python-list mailing list