lambda constructions

graham.matthews@maths.anu.edu.au
29 Jan 1995 22:05:35 GMT

I was wondwering about the 'lambda' construction in Python. It seems to
me thats its semantics are backwards. Say I do something like this,

n = 1
f = lambda x: x + n

I would expect f to be the function f(x)=x+1. This is how a standard
term closure works in a functional language. To get the same effect in
Python I must do,

f = eval("lambda x: x + n", {n:n})

As I think most programmers use lambda constructions as term closures,
I would like to see the default behaviour for lambda constructions changed
to form closures.

I came across this issue in a recent article I posted to the group. In it
I asked,

>I have a binding like this,
>
> self.tag_bind("some_name", "<ButtonRelease-2>", self.do_insert)
>
>I then have my do_insert function as follows,
>
> def do_insert(self, event):
> ...
>
>Is there any way in do_insert of retrieving the string
>"<ButtonRelease-2>"? Alternately is there any way of establishing
>the binding such that this information is easy to access?

The solution to this problem is to use a lambda construction. Say I had
a set of possible event masks (a set of "<ButtonRelease-2>" specifications).
Then I can write this code,

for x in self.event_masks:
self.tag_bind("_an_action", x,
eval("lambda e: e.widget.do_action(e, x)", {'x':x}))

For each event mask I bind a lambda construction containing the event
mask 'x'. While its nice to be able to do this, my first approach to this
problem was to do it without the eval(), simply writing,

for x in self.event_masks:
self.tag_bind("_an_action", x, lambda e: e.widget.do_action(e, x))

Here I was trying to exploit "standard" functional closures (the way I
presumed lambda worked).

graham

--
                      Je suis pour le communisme
                      Je suis pour le socialisme
                      Je suis pour le capitalisme
                     Parce que je suis opportuniste