"eval vs operator.methodcaller" - which is better?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Mar 18 10:23:27 EDT 2013
On Mon, 18 Mar 2013 19:28:37 +0530, Laxmikant Chitare wrote:
> Aha, that was smart Chris. Thank you.
>
> But this raises another question in my mind. What is the use case for
> operator.methodcaller ?
The use-case is mostly to allow people to write code in a functional
style, if they so choose.
import operator
func = operator.methodcaller("spam")
items = map(func, [a, b, c, d])
is the functional-style equivalent of:
items = [obj.spam() for obj in [a, b, c, d]]
methodcaller makes a little more sense if you provide arguments:
func = operator.methodcaller("spam", 1, 2, None, "ham")
items = map(func, [a, b, c, d])
compared to:
items = [obj.spam(1, 2, None, "ham") for obj in [a, b, c, d]]
I expect that the methodcaller version will be very slightly faster in
this case, since it doesn't have to parse the arguments every time the
method is called.
--
Steven
More information about the Python-list
mailing list