Functional Python Programming

(Wang) #1

Functions, Iterators, and Generators


The first example, building a dictionary once, stems from an application with three
operating phases: gather some input, create a dict object, and then process input
based on the mappings in the dictionary. As an example of this kind of application,
we might be doing some image processing and have a specific palette of colors,
represented by names and (R, G, B) tuples. If we use the GNU Image Manipulation
Program (GIMP) GNU General Public License (GPL) file format, the color palette
might look like the following command snippet:


GIMP Palette
Name: Small
Columns: 3



0 0 0 Black
255 255 255 White
238 32 77 Red
28 172 120 Green
31 117 254 Blue


The details of parsing this file are the subject of Chapter 6, Recursions and Reductions.
What's important is the results of the parsing.


First, we'll assume that we're using the following Color namedtuple:


from collections import namedtuple
Color = namedtuple("Color", ("red", "green", "blue", "name"))


Second, we'll assume that we have a parser that produces an iterable of Color
objects. If we materialize it as a tuple, it would look like the following:


(Color(red=239, green=222, blue=205, name='Almond'),
Color(red=205, green=149, blue=117, name='Antique Brass'),
Color(red=253, green=217, blue=181, name='Apricot'),
Color(red=197, green=227, blue=132, name='Yellow Green'),
Color(red=255, green=174, blue=66, name='Yellow Orange'))


In order to locate a given color name quickly, we will create a frozen dictionary
from this sequence. This is not the only way to get fast lookups of a color by name.
We'll look at another option later.


To create a mapping from a tuple, we will use the process(wrap(iterable))
design pattern. The following command shows how we can create the color
name mapping:


name_map= dict( (c.name, c) for c in sequence )

Free download pdf