anonymous functions/expressions without lambda?

Dave Benjamin dave.benjamin at gmail.com
Thu Apr 28 12:40:05 EDT 2005


Michael Hoffman wrote:
> 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

I think you meant to write something like this:

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

Or, if you want to delay binding of the "value" parameter:

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

Cheers,
Dave



More information about the Python-list mailing list