heapreplace, methodcaller

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sat Oct 18 14:37:54 EDT 2008


On Sat, 18 Oct 2008 07:01:26 -0700, bearophileHUGS wrote:

> Hello, I'm experimenting more with Python 2.6 and its numerous changes.
> 
> […]
>
> Regarding the operators module, this syntax: methodcaller('replace',
> 'old', 'new')
> 
> Has this meaning:
> lambda s: s.replace('old', 'new')
> 
> I don't know if methodcaller() is faster than that lambda but:
> - It's not shorter;
> - For me it's not more readable;

Then use the ``lambda``.

Your example has just literal constants.  Let's take this example:

methodcaller(meth, arg_a, arg_b)

which is expressed as ``lambda`` function:

lambda x, m=meth, a=arg_a, b=arg_b: getattr(x, meth)(a, b)

Which is longer and IMHO less readable than `methodcaller()`.

> - If it's faster than the lambda, then maybe CPython can start
> performing a little more optimizations, like turning that tiny lambda
> into inlined code.

How?  The functions in `operator` are meant to be passed directly or to 
to create other functions that are passed as HOFs into other functions.  
So the compiler doesn't know in which functions they are used in the end 
and it's possible that different functions are used there too.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list