Something is rotten in Denmark...

Alain Ketterlin alain at dpt-info.u-strasbg.fr
Thu Jun 2 07:00:53 EDT 2011


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

>> 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 agree it's not intuitive. But where does it say that programming 
> language semantics must always be intuitive?

Nowhere. But going against generally accepted semantics should at least
be clearly indicated. Lambda is one of the oldest computing abstraction,
and they are at the core of any functional programming language. Adding
a quick hack to python and call it "lambda" is just abuse of terminology
(I don't say python is the only abuser, implementing lambda is
difficult; see, e.g., Apple C extension called "blocks" and their
implementation of binding).

> What do you expect this code to do?
>
> a = 42
> funcs = [(lambda x: x+a) for i in range(10)]
> funcs[0](1)
[...]
> Do you agree that `a` should be late bound in this situation?

No, absolutely, definitely not. But hey, I didn't learn programming with
python.

-- Alain.



More information about the Python-list mailing list