Something is rotten in Denmark...
harrismh777
harrismh777 at charter.net
Thu Jun 2 11:55:49 EDT 2011
Steven D'Aprano wrote:
> What do you expect this code to do?
>
> a = 42
> funcs = [(lambda x: x+a) for i in range(10)]
> funcs[0](1)
I do see your point with this... truly... but it did get me to think
about what I *do* expect... and that is that 'a' (for the lambda) will
be whatever 'a' is (now) at the time when the anonymous function is
returned, not later when it is called (not really). If I understand
things correctly, if 'a' references a different simple int object
'later' (before the anonymous function is called) then the result of the
lambda may not be what was expected. In your example, of course, the 'i'
is not relevant. On the other hand, as in callbacks, the whole reason
we want to use the lambda in the first place is because we don't know
what the data will be 'later,' and in fact we really do want
'late-binding' after all. (I guess, I want my cake on a nice china
saucer, with a silver spoon, 'and' I want to eat it too... ) 'magine that!
I know, you're saying "well, duh". But here's the thing... that's
the beauty and the curse of pure functional programming (like haskell)
which (by the way) doesn't have this problem, because doesn't have
mutables as in Python ( nor other languages, non functional ). So, those
of us attempting to morph functional programming over python are having
a little difficulty because what we expect to happen with the lambda in
a list comprehension is adversely affected by our misunderstanding of
python's 'late-binding'. See the whine, here?
kind regards,
m harris
More information about the Python-list
mailing list