How to print lambda result ?

Tino Wildenhain tino at wildenhain.de
Tue Jan 20 13:45:06 CET 2009


Barak, Ron wrote:
> Thanks Tino: your solutions without the lambda work nicely.
> What I still don't understand is why the print does not execute the lambda and prints the result, instead of printing the lambda's object description.
> Bye,
> Ron.

Well its up to the implemention what a class is supposed to return when 
its __str__() is called. Default is what you see. (this is actually
__str__() returning __repr__() which is at its default)

Regards
Tino

> 
> -----Original Message-----
> From: Tino Wildenhain [mailto:tino at wildenhain.de]
> Sent: Tuesday, January 20, 2009 14:22
> To: Barak, Ron
> Cc: python-list at python.org
> Subject: Re: How to print lambda result ?
> 
> Hi,
> 
> Barak, Ron wrote:
>> Hi,
>>
>> Wanting to print the correct plural after numbers, I did the following:
>>
>> for num in range(1,4):
>>     string_ = "%d event%s" % (num,lambda num: num > 1 and "s" or "")
>>     print string_
>>
>> However, instead of getting the expected output:
>>
>> 1 event
>> 2 events
>> 3 events
>>
>> I get:
>>
>> 1 event<function <lambda> at 0x00AFE670>
>> 2 event<function <lambda> at 0x00AFE670>
>> 3 event<function <lambda> at 0x00AFE6B0>
> 
> lambda creates a function so this is the result you are seeing. You would need to call the function to get your result.
> 
> (num,(lambda n: n >1 and "s" or "")(num))
> 
> which is just a quite useless application of lambda :-)
> 
> (num,num >1 and "s" or "")
> 
> or even
> 
> (num,"s" if num >1 else "")
> 
> in python > 2.5
> 
> or in python <3.0:
> 
> (num,"s"*(num >1))
> 
> :-)
> 
> HTH
> Tino

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3241 bytes
Desc: S/MIME Cryptographic Signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20090120/c4713a7d/attachment.bin>


More information about the Python-list mailing list