lambda (and reduce) are valuable

Christopher Subich csubich.spam.block at spam.subich.block.com
Tue Dec 13 10:11:33 EST 2005


Chris Mellon wrote:
> functions with real names is crucial to maintainable code. The only
> reason to ever use a lamdba in Python is because you don't want to
> give a function a name, and that is just not a compelling use case for
> GUI events.

Ah, but that neglects the sheer utility of delayed-evaluation 
expressions.  Consider the key= parameter to list.sort, et. al:

complicated_list.sort(key=lambda x: x[3])

Decorate-sort-undecorate is another way of doing this, but it's also 
boilerplate, involves list copies that have nothing to do with the flow 
of the program itself, and can possibly error (if done naively: key is 
comparable, but complex_list[i][0] isn't comparable, such as sorting a 
list of complex numbers by the real part, if two or more items have the 
same real).

The key= parameter was implemented just to make this sort of thing 
clearer and easier (and, in an odd way, actually more semantically 
explicit).  The utility of a full function for the key= is nice and 
necessary, but simultaneously a lot of the uses are going to be for 
one-off expressions (like item[3]).  There, the idea of a named function 
seems conceptual overkill.

The most significant problem with Python's lambda is that it's billed as 
an anonymous function, when it's really an encapsulated expression.  My 
preferred solution is to replace lambda with something along the lines 
of an 'expression comprehension,' with similar syntax to list and 
generator comprehensions as-is:

lambda param1, param2: stuff_with(param2,param1) would become

<(param1, param2): stuff_with(param2, param1)>
or, to become even more similar to comprehension syntax:
<stuff_with(param2, param1) with (param1, param2)>

The only real problem, parsing-wise, with this syntax is that it can 
sometimes conflict with the << or >> operators if used without 
whitespace near comparisons.

The scope of what can be contained in the expression comprehension 
(lambda currently) is exactly the same as what can be contained in a 
list/generator comprehension, so why not capitalize on the parallelism?



More information about the Python-list mailing list