Functional Python Programming

(Wang) #1

Conditional Expressions and the Operator Module


This is a series expansion based on 4 arctan(1)=π. The expansion is


(^0) ()
2!
n 2 1!!
n
n
π= ∞=
∑ +
An interesting variation to the series expansion theme is to replace the operator.
truediv() function with the fractions.Fraction() function. This will create exact
rational values that don't suffer from the limitations of floating-point approximations.
All of the Python operators are available in the operators module. This includes
all of the bit-fiddling operators as well as the comparison operators. In some cases,
a generator expression may be more succinct or expressive than a rather complex-
looking starmap() function with a function that represents an operator.
The issue is that the operator module provides only a single operator, essentially
a shorthand for lambda. We can use the operator.add method instead of the
add=lambda a,b: a+b method. If we have more complex expressions, then the
lambda object is the only way to write them.


Reducing with operators


We'll look at one more way that we might try to use the operator definitions. We can
use them with the built-in functools.reduce() function. The sum() function, for
example, can be defined as follows:


sum= functools.partial(functools.reduce, operator.add)


We created a partially evaluated version of the reduce() function with the first
argument supplied. In this case, it's the + operator, implemented via the operator.
add() function.


If we have a requirement for a similar function that computes a product, we can
define it like this:


prod= functools.partial(functools.reduce, operator.mul)


This follows the pattern shown in the preceding example. We have a partially
evaluated reduce() function with the first argument of * operator, as implemented
by the operator.mul() function.


It's not clear whether we can do similar things with too many of the other operators.
We might be able to find a use for the operator.concat() function as well as the
operator.and() and operator.or() functions.


The and() and or() functions are the bit-wise & and / operators.
If we want the proper Boolean operators, we have to use the all()
and any() functions instead of the reduce() function.
Free download pdf