Functional Python Programming

(Wang) #1

Additional Tuple Techniques


The preceding code would be changed to the following code snippet:


def float_lat_lon(row_iter):


return (Point(map(float, pick_lat_lon(row)))
for row in row_iter)


This would build Point objects instead of anonymous tuples of floating-point
coordinates.


Similarly, we can introduce the following to build the complete trip of Leg objects:


with urllib.request.urlopen("file:./Winter%202012-2013.kml") as
source:


path_iter = float_lat_lon(row_iter_kml(source))


pair_iter = legs(path_iter)


trip_iter = (Leg(start, end, round(haversine(start, end),4))
for start,end in pair_iter)


trip= tuple(trip_iter)


This will iterate through the basic path of points, pairing them up to make start
and end for each Leg object. These pairs are then used to build Leg instances using
the start point, end point, and the haversine() function from Chapter 4, Working
with Collections.


The trip object will look as follows when we try to print it:


(Leg(start=Point(latitude=37.54901619777347, longitude=
-76.33029518659048), end=Point(latitude=37.840832, longitude=
-76.273834), distance=17.7246),
Leg(start=Point(latitude=37.840832, longitude=-76.273834),
end=Point(latitude=38.331501, longitude=-76.459503),
distance=30.7382),
...


Leg(start=Point(latitude=38.330166, longitude=-76.458504),
end=Point(latitude=38.976334, longitude=-76.473503),
distance=38.8019))


It's important to note that the haversine() function was written to
use simple tuples. We've reused this function with namedtuples. As
we carefully preserved the order the arguments, this small change in
representation was handled gracefully by Python.

In some cases, the namedtuple function adds clarity. In other cases, the namedtuple
is a needless change in syntax from prefix to suffix.

Free download pdf