May 2001
Intermediate to advanced
304 pages
6h 12m
English
The operator module provides a “functional” interface to the
standard operators in Python. The functions in this module can be
used instead of some lambda constructs, when
processing data with functions like map and
filter. They are also quite popular among people who like to write obscure
code, for obvious reasons. The operator module is demonstrated in Example 1-62.
Example 1-62. Using the operator Module
File: operator-example-1.py
import operator
sequence = 1, 2, 4
print "add", "=>", reduce(operator.add, sequence)
print "sub", "=>", reduce(operator.sub, sequence)
print "mul", "=>", reduce(operator.mul, sequence)
print "concat", "=>", operator.concat("spam", "egg")
print "repeat", "=>", operator.repeat("spam", 5)
print "getitem", "=>", operator.getitem(sequence, 2)
print "indexOf", "=>", operator.indexOf(sequence, 2)
print "sequenceIncludes", "=>", operator.sequenceIncludes(sequence, 3)
add => 7
sub => -5
mul => 8
concat => spamegg
repeat => spamspamspamspamspam
getitem => 4
indexOf => 1
sequenceIncludes => 0Example 1-63 shows some operator functions that can be used to check
object types.
Example 1-63. Using the operator Module for Type Checking
File: operator-example-2.py import operator import UserList def dump(data): print type(data), "=>", if operator.isCallable(data): print "CALLABLE", if operator.isMappingType(data): print "MAPPING", if operator.isNumberType(data): print "NUMBER", if operator.isSequenceType(data): print "SEQUENCE", print dump(0) dump("string") ...Read now
Unlock full access