7.1 The operator module The$_{operator}$ module was mentioned earlier. It contains a set of functions corresponding to Python’s operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation. Some of the functions in this module are: • Math operations:$_{add()}$ ,$_{sub()}$ ,$_{mul()}$ ,$_{floordiv()}$ ,$_{abs()}$ , … • Logical operations: not_() , truth() . • Bitwise operations: and_() , or_() , invert() . • Comparisons: eq() , ne() , lt() , le() , gt() , and ge() . • Object identity: is_() , is_not() . 8 Small functions and the lambda expression Consult the operator module’s documentation for a complete list. When writing functional-style programs, you’ll often need little functions that act as predicates or that combine ele- ments in some way. If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all: stripped_lines=[line.strip() for line in lines] existing_files=filter(os.path.exists, file_list) If the function you need doesn’t exist, you need to write it. One way to write small functions is to use the$_{lambda}$ expression. $_{lambda}$takes a number of parameters and an expression combining these parameters, and creates an anonymous function that returns the value of the expression: adder = lambda x, y: x +y print_assign= lambda name, value: name +'='+str(value) An alternative is to just use the$_{def}$ statement and define a function in the usual way: Which alternative is preferable? That’s a style question; my usual course is to avoid using$_{lambda}$ . One reason for my preference is that$_{lambda}$is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can’t have multiway$_{if... elif... else}$ comparisons or$_{try... except}$ statements. If you try to do too much in a$_{lambda}$statement, you’ll end up with an overly complicated expression that’s hard to read. Quick, what’s the following code doing? import functools total=functools .reduce( lambda a, b: ( 0, a[1] +b[1]), items)[ 1] You can figure it out, but it takes time to disentangle the expression to figure out what’s going on. Using a short nested $_{def}$statements makes things a little bit better: (continues on next page) import functools def combine(a, b): return 0, a[1] +b[1] def adder(x, y): return x +y def print_assign(name, value): return name +'='+str(value) 17