[Python-Dev] Lambda [was Re: PEP 8 modernisation]

Alexander Shorin kxepal at gmail.com
Thu Aug 1 18:58:07 CEST 2013


Hi Steven,

On Thu, Aug 1, 2013 at 7:06 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> Hi Alexander,
>
> On 02/08/13 00:48, Alexander Shorin wrote:
>>
>> Hi Ronald,
>>
>> I understand this, but I'm a bit confused about fate of lambdas with
>> such guideline since I see no more reasons to use them with p.9
>> statement: long lines, code duplicate, no mock and well tests etc. -
>> all these problems could be solved with assigning lambda to some name,
>> but now they are looks useless (or useful only for very trivial cases)
>
>
> Lambda is still useful for the reason lambda has always been useful: it is
> an expression, not a statement, so you can embed it directly where needed.
>
> # Preferred:
> sorted(data, key=lambda value: value['spam'].casefold())
>
> # Allowed:
> def f(value): return value['spam'].casefold()
> sorted(data, key=f)
>
> # Prohibited:
> f = lambda value: value['spam'].casefold()
> sorted(data, key=f)
>
> # SyntaxError:
> sorted(data, key=def f(value): value['spam'].casefold())

The case:

items =  [[0, 'foo'], [3, 'baz'],  [2, 'foo'], [1, 'bar']]

Need to group by second item. Quite common task:

>>> from itertools import groupby
>>>
>>> for key, items in groupby(items, key=lambda i: i[1]):
>>>   print(key, ':', list(items))
foo : [[0, 'foo']]
baz : [[3, 'baz']]
foo : [[2, 'foo']]
bar : [[1, 'bar']]

oops, failed, we need to sort things first by this item and it looks
we have to duplicate grouping function:

fun = lambda i: i[1]
for key, items in groupby(sorted(items, key=fun), key=fun):
  print(key, ':', list(items))

Ok, PEP suggests to use defs, so we adds 3 more lines (before and
after def + return) to code:

def fun(i):
  return i[1]

for key, items in groupby(sorted(items, key=fun), key=fun):
  print(key, ':', list(items))

so that's the question: what is the rationale of this if lambdas
successfully solves the problem with minimal amount of typing, code
and thinking? I thought there should be only one way to do something,
but this PEP-8 statement conflicts with PEP-20 one:

> There should be one-- and preferably only one --obvious way to do it.

It's really not oblivious why lambdas couldn't be assignment to some
name, especially in the light of fact that if they are been passed to
some function as argument, they will be assignee to some name.



--
,,,^..^,,,


More information about the Python-Dev mailing list