Functional Python Programming

(Wang) #1

Conditional Expressions and the Operator Module


The use of the lambda x,y: xy parameter seems a bit wordy for multiplication.
After all, we just want to use the multiplication operator,
. Can we simplify the
syntax? The answer is yes; the operator module provides us with definitions
of the built-in operators.


There are a number of features of the operator module that lead to some
simplification and potential clarification to create higher-order functions. While
important conceptually, the operator module isn't as interesting as it initially appears.


Evaluating conditional expressions


Python imposes relatively strict ordering on expressions; the notable exceptions are
the short-circuit operators, and and or. It imposes very strict ordering on statement
evaluation. This makes it challenging to find different ways to avoid this strict
evaluation.


It turns out that evaluating condition expressions is one way in which we can
experiment with non-strict ordering of statements. We'll examine some ways to
refactor the if and else statements to explore this aspect of non-strict evaluation
in Python.


The Python if, elif, and else statements are evaluated in a strict order from first to
last. Ideally, a language might relax this rule so that an optimizing compiler can find
a faster order for evaluating the conditional expressions. The idea is for us to write
the expressions in an order that makes sense to a reader, even if the actual evaluation
order is non-strict.


Lacking an optimizing compiler, this concept is a bit of a stretch for Python.
Nonetheless, we do have alternative ways to express conditions that involve the
evaluation of functions instead of the execution of imperative statements. This can
allow you to make some rearrangement at runtime.


Python does have a conditional if and else expression. This expression form can be
used when there's a single condition. When we have multiple conditions, however,
it can get awkwardly complex: we'd have to carefully nest the subexpressions. We
might wind up with a command, as follows, which is rather difficult to comprehend:


(x if n==1 else (y if n==2 else z))

Free download pdf