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

Michael Hudson mwh at python.net
Fri Feb 3 10:36:30 CET 2006

Alex Martelli <aleaxit at gmail.com> writes:

> I was recently reviewing a lot of the Python 2.4 code I have written,
> and I've noticed one thing: thanks to the attrgetter and itemgetter
> functions in module operator, I've been using (or been tempted to use)
> far fewer lambdas, particularly but not exclusively in key= arguments
> to sort and sorted.

Interesting.  Something I'd noticed was that *until* the key= argument
to sort appeared, I was hardly using any lambdas at all (most of the
places I had used them were rendered obsolete by list comprehensions).

> Most of those "lambda temptations" will be
> removed by PEP 309 (functional.partial), and most remaining ones are
> of the form:
>     lambda x: x.amethod(zip, zop)
> So I was thinking -- wouldn't it be nice to have (possibly in module
> functional, like partial; possibly in module operator, like itemgetter
> and attrgetter -- I'm partial to functional;-) a methodcaller entry
> akin to (...possibly with a better name...):
> def methodcaller(methodname, *a, **k):
>     def caller(self):
>         getattr(self, methodname)(*a, **k)
>     caller.__name__ = methodname
>     return caller
> ...?  This would allow removal of even more lambdas.
> 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...


>>> 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).

A class I wrote (and lost) ages ago was a "placeholder" class, so if
'X' was an instance of this class, "X + 1" was roughly equivalent to
"lambda x:x+1" and "X.method(zip, zop)" was roughly equivalent to your
"methodcaller("method", zip, zop)".  I threw it away when listcomps
got implemented.  Not sure why I mention it now, something about your
post made me think of it...


  If you give someone Fortran, he has Fortran.
  If you give someone Lisp, he has any language he pleases.
    -- Guy L. Steele Jr, quoted by David Rush in comp.lang.scheme.scsh

More information about the Python-Dev mailing list