anonymous functions/expressions without lambda?

Michael Hoffman cam.ac.uk at mh391.invalid
Thu Apr 28 11:28:13 EDT 2005


Paul Miller wrote:

 > I see lambda is "going away", so I want to use something that will be 
 > around for awhile.
 >
 > All I want to do is provide an "inline function" as an argument to
 > another function.

That's what lambda does. But it's going away, you'll have to use def 
when it does, unless the language designers come up with something better.

> For example, let's say I have a function which binds a key to a function 
> call. I want to do something "simple" in this function call, and I have 
> a lot of bindings, so I don't want to have a ton of tiny little 
> functions scattered around:
> 
>     def setVarTo1():
>         foo.var = 1
>     def setVarTo2():
>         foo.var = 2
> 
>     bind('a', setVarTo1)
>     bind('b', setVarTo2)

If a lot of the bindings are actually setting variables, you could do 
something like this:

def attrsetter(obj, name, 1):
     def _return_func(value):
         return setattr(obj, name, value)

     return _return_func

> Instead, I'd like to do something like this:
> 
>     bind('a', foo.var = 1)
>     bind('b', foo.var = 2)

bind('a', attrsetter(foo, "var", 1))
bind('a', attrsetter(foo, "var", 2))
-- 
Michael Hoffman



More information about the Python-list mailing list