[Tutor] lambda

eryksun eryksun at gmail.com
Sat Jan 26 02:22:02 CET 2013


On Fri, Jan 25, 2013 at 7:14 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> Your problem of course is that you need i and j to be dynamically defined so
> you need to create and call a function that returns a function like this
>
> def buttonFunMaker(i,j):
>     def func(x=i,y=j):
>         return ttt(x,y)
>     return func
>
> b[i][j] = Button(font=('Aerial', 56), width=3, bg='yellow',
>                  command = buttonFunMaker(i,j))

With a function call you no longer need the default parameter hack
(i.e. x=i, y=j). You can make a closure over the local i and j in
buttonFunMaker:

    def buttonFunMaker(i, j):
        def func():
            return ttt(i, j)
        return func

or:

    def buttonFunMaker(i, j):
        return lambda: ttt(i, j)

With only lambda expressions, this structure is a bit awkward:

    command=(lambda i, j: lambda: ttt(i, j))(i, j)


More information about the Tutor mailing list