views:

255

answers:

2

I'm speaking of this module: http://docs.python.org/library/operator.html

From the article:

The operator module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.

I'm not sure I understand the benefit or purpose of this module.

+4  A: 

One example is in the use of the reduce() function:

>>> import operator
>>> a = [2, 3, 4, 5]
>>> reduce(lambda x, y: x + y, a)
14
>>> reduce(operator.add, a)
14
Greg Hewgill
+8  A: 

Possibly the most popular usage is operator.itemgetter. Given a list lst of tuples, you can sort by the ith element by: lst.sort(key=operator.itemgetter(i))

Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.

As to the rest, python allows a functional style of programming, and so it can come up -- for instance, Greg's reduce example.

You might argue: "Why do I need operator.add when I can just do: add = lambda x, y: x+y?" The answers are:

  1. operator.add is (I think) slightly faster.
  2. It makes the code easier to understand for you, or another person later, looking at it. They don't need to look for the definition of add, because they know what the opeartor module does.
John Fouhy