Functional Python Programming

(Wang) #1
Chapter 4

Adding a filter extension to this design might look something like the following
code snippet:


def legs_filter(lat_lon_iter):
begin= next(lat_lon_iter)
for end in lat_lon_iter:
if #some rule for rejecting:
continue
yield begin, end
begin= end


We have plugged in a processing rule to reject certain values. As the loop remains
succinct and expressive, we are confident that the processing will be done properly.
Also, we can easily write a test for this function, as the results work for any iterable,
irrespective of the long-term destination of the pairs.


The next refactoring will introduce additional mapping to a loop. Adding mappings
is common when a design is evolving. In our case, we have a sequence of string
values. We need to convert these to floating-point values for later use. This is a
relatively simple mapping that shows the design pattern.


The following is one way to handle this data mapping, through a generator
expression that wraps a generator function:


print(tuple(legs((float(lat), float(lon))
for lat,lon in lat_lon_kml())))


We've applied the legs() function to a generator expression that creates float
values from the output of the lat_lon_kml() function. We can read this in the
opposite order as well. The lat_lon_kml() function's output is transformed
into a pair of float values, which is then transformed into a sequence of legs.


This is starting to get complex. We've got a large number of nested functions here.
We're applying float(), legs(), and tuple() to a data generator. One common
refactoring of complex expressions is to separate the generator expression from
any materialized collection. We can do the following to simplify the expression:


flt= ((float(lat), float(lon)) for lat,lon in lat_lon_kml())
print(tuple(legs(flt)))


We've assigned the generator function to a variable named flt. This variable
isn't a collection object; we're not using a list comprehension to create an object.
We've merely assigned the generator expression to a variable name. We've then
used the flt variable in another expression.

Free download pdf