[Python-Dev] lambda (x, y):

Eric V. Smith eric at trueblade.com
Sun Jan 26 18:16:30 CET 2014


On 01/26/2014 09:59 AM, francis wrote:
> On 01/26/2014 03:42 AM, Raymond Hettinger wrote:
>>
>> I think that is an over-simplification.  The argument unpacking was handy
>> in a number of situations where *args wouldn't suffice:
>>
>>    lambda (px, py), (qx, qy): ((px - qx) ** 2 + (py - qy) ** 2) ** 0.5
>>
>> IIRC, the original reason for the change was that it simplified the
>> compiler a bit,
>> not that it was broken or not useful.
> I'm not sure if that's applicable or other issues arise with:
> 
> def fn(*p): px,py,qx,qy = p; return ((px - qx) ** 2 + (py - qy) ** 2) **
> 0.5

[Dropping some whitespace to get things to all fit on one line]

The goal is to call fn as:
fn((1, 1), (2, 2))

So, in 2.7:
>>> def fn((px, py), (qx, qy)):
...   return ((px-qx)**2+(py-qy)**2)**0.5
...
>>> fn((1, 1), (2, 2))
1.4142135623730951
>>>

The nearest equivalent in 3.3 (also works in 2.7):
>>> def fn(p, q):
...   (px, py), (qx, qy) = p, q
...   return ((px-qx)**2+(py-qy)**2)**0.5
...
>>> fn((1, 1), (2, 2))
1.4142135623730951

For a lambda in 3.3, you're out of luck because you can't do the
assignment. There, the best you can do is:
>>> fn = lambda p, q: ((p[0]-q[0])**2+(p[1]-q[1])**2)**0.5
>>> fn((1, 1), (2, 2))
1.4142135623730951

Which isn't quite so readable as the equivalent lambda in 2.7:
>>> fn = lambda (px, py),(qx, qy):((px-qx)**2+(py-qy)**2)**0.5
>>> fn((1, 1), (2, 2))
1.4142135623730951

As someone pointed out, it's not quite the same when you do your own
tuple unpacking, but it's probably close enough for most cases.

Eric.



More information about the Python-Dev mailing list