Functional Python Programming

(Wang) #1
Chapter 5

This function steps through the items in the iterable. It attempts to apply the function
to the item; if no exception is raised, this new value is yielded. If an exception is
raised, the offending value is silently dropped.


This can be handy when dealing with data that include values that are not applicable
or missing. Rather than working out complex filters to exclude these values, we
attempt to process them and drop the ones that aren't valid.


We might use the map() function for mapping not-None values as follows:


data = map_not_none(int, some_source)


We'll apply the int() function to each value in some_source. When the
some_source parameter is an iterable collection of strings, this can be a handy
way to reject strings that don't represent a number.


Building higher-order functions with Callables


We can define higher-order functions as instances of the Callable class. This builds
on the idea of writing generator functions; we'll write callables because we need
statement features of Python. In addition to using statements, we can also apply a
static configuration when creating the higher-order function.


What's important about a Callable class definition is that the class object, created by
the class statement, defines essentially a function that emits a function. Commonly,
we'll use a callable object to create a composite function that combines two other
functions into something relatively complex.


To emphasize this, consider the following class:


from collections.abc import Callable


class NullAware(Callable):


def init(self, some_func):


self.some_func= some_func


def call(self, arg):


return None if arg is None else self.some_func(arg)


This class creates a function named NullAware() that is a higher-order function
that is used to create a new function. When we evaluate the NullAware(math.log)
expression, we're creating a new function that can be applied to argument values.
The init() method will save the given function in the resulting object.

Free download pdf