Parameterized functions of no arguments?

Paul Rubin at nospam.invalid
Fri Feb 11 09:07:38 CET 2011

Dennis Lee Bieber <wlfraed at> writes:
>>          menu.add_command(label = str(k), command = lambda: f(k))
> 	I'm not sure, but what effect does
> 		menu.add_command(label=str(k), command = lambda k=k: f(k))
> have on the processing.

In the first example, k is a free variable in the lambda, so it's
captured from the outer scope when the lambda is evaluated:

    >>> k = 3
    >>> a = lambda: k
    >>> k = 5
    >>> a()

In the second example, k is bound as an arg to the lambda when the
lambda runs, initialized to the default value supplied when the lambda
was created:

    >>> k = 3
    >>> a = lambda k=5: k
    >>> a()

In the weird looking k=k syntax, the "=k" gets k from the outer scope,
and uses it as a default value for the function arg that is bound in the
function.  I.e. if k=3 then lambda k=k: ...  is like lambda k=3:...

More information about the Python-list mailing list