Draft Pep (was: Re: Let's Talk About Lambda Functions!)

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Mon Aug 5 14:42:13 EDT 2002


François Pinard <pinard at iro.umontreal.ca> wrote:
>[John Roth]
>
>> Rationale
>
>>     There is a continuous interest in generalizing the lambda() function,
>>     which has significant limitations.  Most of the proposals to date
>>     have attempted to invent additional syntax to allow fewer restrictions
>>     while still maintaining the expression format of lambda().
>
>The rumour states that Guido regrets having added `lambda' to Python.
>I guess it goes beyond the mere `lambda' keyword: it is reasonable to
>think that what Guido regrets is the addition of anonymous functions.
>
>If the rationale is essentially reduced to the vague statement of a
>"continuous interest", it is a pretty weak rationale.  Before anything
>else, the rationale should stress, in very convincing ways, why anonymous
>functions should grow stronger in Python, instead of being faded out.
>
>Also, recent additions in Python are said to significantly alleviate most
>of the need for anonymous functions, so the rationale of this PEP might
>explain why these additions are still not satisfactory on that respect.

These are excellent comments.  It is important to spell out some of the
actual benefits of anonymous functions.  Following is one aspect that might
be useful for the PEP.

It is often said that "table-driven programming" is more readable and easier
to maintain than deeply nested flow control structures.  Witness the other
thread discussing the relative merits of if/elif/else versus switch
statement versus dictionary-based dispatcher.  The tenet of this programming
style is that the flow control is driven by various entries in a data
structure, instead of hard-coded in the program.  For this type of programs,
there are many benefits to be able to define a function exactly where it
appears inside a data structure.  Currently Python allows this to be done
only if such a function involves only a single expression.  This leads to
inconsistent styles like

def func1 ...
def func3 ...
def func4 ...

callbacks = {
   "case a": func1,
   "case b": lambda ...
   "case c": func3,
   "case d": func4,
   "case e": lambda ...
}

Pulling functions out of data structures not only pollutes module name
spaces with unwanted names, but also splits semantically connected material
to separate locations in the code.

Allowing full-blown anonymous functions can solve this problem.   The above
code would become

callbacks = {
   "case a": def ...
   "case b": def ...
   "case c": def ...
   "case d": def ...
   "case e": def ...
}

Do Python's recent additions, such as list comprehension, make this wanted
feature redundent?  I don't think so (but would like to see examples showing
otherwise).  In fact I think the availability of nested scopes makes this
even a more appealing style.

Huaiyu





More information about the Python-list mailing list