what's wrong with "lambda x : print x/60,x%60"

Fredrik Lundh fredrik at pythonware.com
Tue Dec 6 06:10:39 EST 2005


Steve Holden wrote:

> One perhaps needs to be a little more careful with instance variables,
> but again most *temporaries* are simply local to the method in which
> they're called, they don't exist for the lifetime of the instance.

and more importantly, temporary variables can be reused.  they're only
bound to a given object until you bind them to some other object.  the
following is a perfectly good way to define a couple of callbacks:

    def callback():
        ...
    b1 = Button(master, command=callback)

    def callback():
        ...
    b2 = Button(master, command=callback)

    def callback():
        ...
    b3 = Button(master, command=callback)

(three callbacks, a single temporary name)

to refer to variables from the outer scope from inside a callback,
just use the variable.  to refer to *values* from the outer scope,
use argument binding:

    def callback(arg=value):
        ...
    b3 = Button(master, command=callback)

since "def" is an executable statement, and the argument line is
part of the def statement, you can bind the same argument to
different values even for the same function, e.g.

    for i in range(10):
        def callback(button_index=i):
            ...
        b = Button(master, command=callback)

this loop creates ten distinct function objects.

</F>






More information about the Python-list mailing list