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

Bengt Richter bokr at oz.net
Mon Dec 5 06:46:58 EST 2005


On Mon, 05 Dec 2005 10:38:25 +0100, bruno at modulix <onurb at xiludom.gro> wrote:

>Gary Herron wrote:
>> Mohammad Jeffry wrote:
>> 
>>> Dear All,
>>>
>>> Can't a lambda uses the input parameter more then once in the lambda
>>> body?
>>> eg:
>>> lambda x : print x/60,x%60
>>>
>>> I tried with def and it works but got syntax error with lambda. Below
>>> is an interactive sample:
>> 
>> 
>> Lambda evaluates a single *expression* and returns the result.  As print
>> is a statement it does not qualify (and would provide nothing to return
>> even if it did).  So just use a def. 
>
>or use sys.stdout.write in your lambda:
>import sys
>lambda x : sys.stdout.write("%d %d\n" % (x/60, x%60))
>
>> It is constantly pointed out on
>> this list that the lambda provides no extra expressive power, 
>
>They do, when one need a very trivial callable for callbacks - which is
>probably the main (if not the only) use case.
>
>> it is
>> merely a shortcut and, as you just found out, a rather restrictive one
>> at that.
>
>Of course.
>
If you think lambda is restrictive, you can use dumbda:

 >>> def dumbda(src):
 ...     d = {}
 ...     exec src in d
 ...     for k,v in d.items():
 ...         if callable(v): return v
 ...     else:
 ...         raise ValueError('dumbda produced no callable from:\n%s'%src)
 ...
 >>> f = dumbda("def foo(x): print 'foo(%r)'%x")
 >>> f('hello foo')
 foo('hello foo')

I'd prefer an "anonymous def" though ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list