[Python-Dev] any support for a methodcaller HOF?

Nick Coghlan ncoghlan at gmail.com
Fri Feb 3 11:44:47 CET 2006


Michael Hudson wrote:
> Alex Martelli <aleaxit at gmail.com> writes:
>> I'll be glad to write a PEP, but I first want to check whether the
>> Python-Dev crowd would just blast it out of the waters, in which case
>> I may save writing it...
> 
> Hmm.
> 
>>>> funcTakingCallback(lamda x:x.method(zip, zop))
>>>> funcTakingCallback(methodcaller("method", zip, zop))
> 
> I'm not sure which of these is clearer really.  Are lambdas so bad?
> (FWIW, I haven't internalized itemgetter/attrgetter yet and still tend
> to use lambdas instead those too).

I've been convinced for a while that the proliferation of features like 
operator.itemgetter and attrgetter (and some uses of functional.partial) 
demonstrate that the ability to defer a single expression (as lambda currently 
allows) is a very useful feature to have in the language. Unfortunately that 
utility gets overshadowed by the ugliness of the syntax, the mathematical 
baggage associated with the current keyword, and the fact that lambda gets 
pitched as an "anonymous function limited to a single expression", rather than 
as "the ability to defer an expression for later evaluation" (the former 
sounds like a limitation that should be fixed, the latter sounds like the 
deliberate design choice that it is).

At the moment it looks like the baby is going to get thrown out with the 
bathwater in Py3k, but I'd love to be able to simply write the following 
instead of some byzantine mixture of function calls to get the same effect:

     funcTakingCallback(x.method(zip, zop) def (x))

Consider these comparisons:

   itemgetter(1)     <=> (x[1] def (x))
   attrgetter('foo') <=> (x.foo def (x))
   partial(y, arg)   <=> (y(arg) def)

So rather than yet another workaround for lambda being ugly, I'd rather see a 
PEP that proposed "Let's make the syntax for deferring an expression not be 
ugly anymore, now that we have generator expressions and conditionals as an 
example of how to do it right".

Guido was rather unenthused the last time this topic came up, though, so maybe 
it isn't worth the effort. . . (although he did eventually change his mind on 
PEP 308, so I haven't entirely given up hope yet).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list