Functional Python Programming

(Wang) #1
Chapter 3

Where the sequence variable is the iterable of the Color objects shown previously,
the wrap() element of the design pattern simply transforms each Color object , c,
into the two tuple (c.name, c). The process() element of the design uses dict()
initialization to create a mapping from name to Color. The resulting dictionary looks
as follows:


{'Caribbean Green': Color(red=28, green=211, blue=162,
name='Caribbean Green'),
'Peach': Color(red=255, green=207, blue=171, name='Peach'),
'Blizzard Blue': Color(red=172, green=229, blue=238, name='Blizzard
Blue'),


The order is not guaranteed, so you may not see Caribbean Green first.


Now that we've materialized the mapping, we can use this dict() object in some
later processing for repeated transformations from color name to (R, G, B) color
numbers. The lookup will be blazingly fast because a dictionary does a rapid
transformation from key to hash value followed by lookup in the dictionary.


Using the bisect module to create a mapping


In the previous example, we created a dict mapping to achieve a fast mapping from
a color name to a Color object. This isn't the only choice; we can use the bisect
module instead. Using the bisect module means that we have to create a sorted
object, which we can then search. To be perfectly compatible with the dict mapping,
we can use collections.abc.Mapping as the base class.


The dict mapping uses a hash to locate items almost immediately. However,
this requires allocating a fairly large block of memory. The bisect mapping does a
search, which doesn't require as much memory, but performance can be described
as immediate.


A static mapping class looks like the following command snippet:


import bisect
from collections.abc import Mapping
class StaticMapping(Mapping):
def init( self, iterable ):
self._data = tuple(iterable)
self.keys = tuple(sorted(key for key, in self._data))


def getitem(self, key):
ix= bisect.bisect_left(self._keys, key)
if ix != len(self._keys) and self._keys[ix] == key:
return self._data[ix][1]

Free download pdf