Securing a future for anonymous functions in Python

Jeff Shannon jeff at ccvcorp.com
Thu Dec 30 20:39:06 EST 2004


Bengt Richter wrote:

> On Thu, 30 Dec 2004 15:15:51 -0800, Jeff Shannon <jeff at ccvcorp.com> wrote:
> 
>>Mimicking function-def indentation inside of another function's arglist 
>>strikes me as an abomination just waiting to happen; in comparison, the 
>>need to type a name twice seems trivial.
> 
> Self-restraint can avoid abominations ;-)

It can, but given the prevalence of lambda abominations (such as the 
many that the Martellibot described among Cookbook submissions), is 
there any reason to believe that there would be *more* restraint in 
using a less-constrained feature??  :)

>>As a result, it seems to me that, rather than generalize lambdas into 
>>"full" anonymous functions (with most of the negatives and few of the 
>>positives of lambda), it would be much better to specialize them further 
>>into inline-closure-creators, where they can serve a valuable purpose 
>>without quite as much risk of  code pollution.
> 
> (BTW, again, by closure, do you really mean deferred-action-thingie?)

My understanding of "closure" (which may well be wrong, as I've 
inferred it entirely from past discussions on this newsgroup) is that 
it's a callable with some or all of its parameters already set; e.g.,

     def one_and(foo):
         def closure(arg):
             return foo(1, arg)
         return closure

     incr = one_and(operator.add)

The function one_and() returns a closure, here bound to incr.  It is 
essentially a (partially) deferred action thingy, if you want to use 
technical terms. ;)  I suppose that one could look at it as the 
environment in which to call a given function, exported for later use...

My thesis here is that one of the most common (legitimate) uses of 
lambda is as an adapter, to create an intermediary that allows a 
callable with a given signature to be used in places where a different 
signature is expected -- that is, altering the number or order of 
arguments passed to a given callable (and possibly also capturing the 
current value of some other variable in the process).  I feel that 
it's more fruitful to focus on this "adapter" quality rather than 
focusing on the "anonymous function" quality.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list