Functional Python Programming

(Wang) #1

Functions, Iterators, and Generators


raise ValueError("{0!r} not found".format(key))
def iter(self):
return iter(self._keys)
def len(self):
return len(self._keys)


This class extends the abstract superclass collections.abc.Mapping. It provides
an initialization and implementations for three functions missing from the abstract
definition. The getitem() method uses the bisect.bisect_left() function to
search the collection of keys. If the key is found, the appropriate value is returned. The
iter() method returns an iterator, as required by the superclass. The len()
method, similarly, provides the required length of the collection.


Another option is to start with the source code for the collections.OrderedDict
class, change the superclass to Mapping instead of MutableMapping, and remove all
of the methods that implement mutability. For more details on which methods to
keep and which to discard, refer to the Python Standard Library, section 8.4.1.


Visit the following link for more details:


https://docs.python.org/3.3/library/collections.abc.html#collections-
abstract-base-classes


This class might not seem to embody too many functional programming principles.
Our goal here is to support a larger application that minimizes the use of stateful
variables. This class saves a static collection of key-value pairs. As an optimization,
it materializes two objects.


An application that creates an instance of this class is using a materialized object to
perform rapid lookups of the keys. The superclass does not support updates to the
object. The collection, as a whole, is stateless. It's not as fast as the built-in dict class,
but it uses less memory and, through the formality of being a subclass of Mapping,
we can be assured that this object is not used to contain a processing state.


Using stateful sets


Python offers several stateful collections, including the set collection. For our
purposes, there are two use cases for a set: a stateful set that accumulates items,
and a frozenset that is used to optimize searches for an item.


We can create a frozenset from an iterable in the same way as we create a tuple
object from an iterable fronzenset(some_iterable) method; this will create a
structure that has the advantage of a very fast in operator. This can be used in
an application that gatheres data, creates a set, and then uses that frozenset to
process some other data items.

Free download pdf