Functional Python Programming

(Wang) #1
Chapter 7

These definitions don't provide much guidance on the data types involved. We can
use a simple naming convention to make this a bit more clear. The following are
some examples of selection functions that use a suffix:


start_point = lambda leg: leg[0]


distance_nm= lambda leg: leg[2]


latitude_value= lambda point: point[0]


When used judiciously, this can be helpful. It can also degenerate into an elaborately
complex Hungarian notation as a prefix (or suffix) of each variable.


The second technique uses the parameter notation to conceal some details of the
index positions. The following are some selection functions that use the
notation:


start= lambda start, end, distance: start


end= lambda start, end, distance: end


distance= lambda start, end, distance: distance


latitude= lambda lat, lon: lat


longitude= lambda lat, lon: lon


With these definitions, we can use latitude(start(first_leg)) to refer to a
specific piece of data. This has the advantage of clarity. It can look a little odd to see
the * operator in front of the tuple arguments to these selection functions.


The third technique is the namedtuple function. In this case, we have nested
namedtuple functions such as the following:


Leg = namedtuple("Leg", ("start", "end", "distance"))
Point = namedtuple("Point", ("latitude", "longitude"))

This allows us to use first_leg.start.latitude to fetch a particular piece of data.
The change from prefix function names to postfix attribute names can be seen as a
helpful emphasis. It can also be seen as a confusing shift in the syntax.


We will also replace tuple() functions with appropriate Leg() or Point() function
calls in our process that builds the raw data. We will also have to locate some return
and yield statements that implicitly create tuples.


For example, take a look at the following code snippet:


def float_lat_lon(row_iter):


return (tuple(map(float, pick_lat_lon(*row)))
for row in row_iter)

Free download pdf