Python is Considered Harmful
Alex Martelli
aleax at aleax.it
Mon Oct 27 06:14:52 EST 2003
Isaac To wrote:
...
> Did you really mean
>
> map(lambda f: f(1), [lambda x: x+i for i in range(3)])
>
> ? If so, it does return [3, 3, 3]. The only problem here is that Python
> variables are name lookups over dictionaries, and as such the value of "i"
> is not coined into the lambda. Rather it is "external", binded
> dynamically. I believe the behaviour can be fixed rather easily by some
> directives, say making it
>
> map(lambda f: f(1), [lambda x: x+(*i) for i in range(3)])
>
> where the * construct would get the reference of i at function definition
> time rather than at function invocation time (anyone can point me to an
> PEP?). On the other hand, I basically never use lambda this way.
No new "directive" needed: it's easy to get "snap-shots" of current
values of names into a lambda or other function:
map(lambda f: f(1), [lambda x, i=i: x+i for i in range(3)])
The "i=i" gets the (outer) value of i at function-definition time and
injects it as local variable i in the lambda. You can also rename just
as easily (and sometimes it's clearer):
map(lambda f: f(1), [lambda x, k=i: x+k for i in range(3)])
Alex
More information about the Python-list
mailing list