"eval vs operator.methodcaller" - which is better?

Chris Angelico rosuav at gmail.com
Mon Mar 18 10:03:03 EDT 2013


On Tue, Mar 19, 2013 at 12:58 AM, Laxmikant Chitare
<laxmikant.general at gmail.com> wrote:
> Aha, that was smart Chris. Thank you.
>
> But this raises another question in my mind. What is the use case for
> operator.methodcaller ?

Most of the operator module is functional versions of what can be done
elsewhere with operators. They're not generally needed unless you
specifically need a function, such as for a map() call:

>>> a=[1,2,3,4,5]
>>> b=[50,40,30,20,10]
>>> list(map(operator.add,a,b))
[51, 42, 33, 24, 15]

(The list() call is unnecessary in Python 2, but means this will also
work in Python 3.)

ChrisA



More information about the Python-list mailing list