< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162146120131238196102016122

operator

The operator module stores functions that access the built-in standard operators. The main reason for the operator module is that operator.add, for instance, is much faster than lambda a,b: a+b.

For example, the line

					
>>> import operator
>>> operator.div(6,2)
3

				

provides the same result that the next line does.

					
>>> 6 / 2
3

				

This module is mostly used when it becomes necessary to pass an operator as the argument of a function. For example

					
1: import sys, glob, operator
2: sys.argv = reduce(operator.add, map(glob.glob, sys.argv))
3: print sys.argv

				

To run the previous example, save the code in a file and execute it by switching to your OS prompt and typing:

					
python yourfilename.py *.*

				

The heart of this example is Line 2. Let's interpret it:

The glob.glob() function is applied for each element of the original sys.argv list object (by using the map() function). The result is concatenated and reduced into a single variable sys.argv. The concatenation operation is performed by the operator.add() function.


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

functions
      glob.glob()
      map()
      operator.add()
glob.glob() function
libraries
      Python Services
map() function
modules
      operator
operator module
operator.add() function
Python Services

© 2002, O'Reilly & Associates, Inc.