lambda & scope

John J. Lee phrxy at csv.warwick.ac.uk
Mon Nov 6 15:12:34 EST 2000


On 5 Nov 2000, Alex wrote:

>
> Pass the variable value as a default argument:
>
> lambda x, scale=scale, x * scale, v
>
> But for that particular fragment, in python2.0, you would be better off
> going for a list comprehension:
>
> def fred(scale):
>     v = [1, 2, 3]
>     v = [x*scale for x in v]
[...]

say you have:

def fred(variable, parameter):
    return parameter*variable**2

and you want to do something in the spirit of:

def wilma():
    (...)
    parameter = 3.4
    call_fred(lambda x: wilma(x, parameter), args, args, args)

Because you know that call_fred wants as its first argument a function
that only takes one argument (above doesn't work due to Python's
three-level scope).

Probably 'don't do that' is a good answer, but I wondered if there was
another one?  Actually I think there is a way that would work in Mark
Lutz's book, using a class, but is there a simpler way?


John




More information about the Python-list mailing list