Functional Python Programming

(Wang) #1

Introducing Some Functional Features


Since the max() function is a higher-order function, we can provide another function
as an argument. In this case, we'll use lambda as the function; this is used by the
max() function, as follows:





max(year_cheese, key=lambda yc: yc[1])





(2007, 33.5)


In this example, the max() function applies the supplied lambda and returns the
tuple with the largest value in position 1.


Python provides a rich collection of higher-order functions. We'll see examples
of each of Python's higher-order functions in later chapters, primarily in Chapter 5,
Higher-order Functions. We'll also see how we can easily write our own higher-order
functions.


Immutable data


Since we're not using variables to track the state of a computation, our focus needs to
stay on immutable objects. We can make extensive use of tuples and namedtuples
to provide more complex data structures that are immutable.


The idea of immutable objects is not foreign to Python. There can be a performance
advantage to using immutable tuples instead of more complex mutable objects.
In some cases, the benefits come from rethinking the algorithm to avoid the costs
of object mutation.


We will avoid class definitions (almost) entirely. It can seem like it's anathema to
avoid objects in an Object-Oriented Programming (OOP) language. Functional
programming simply doesn't need stateful objects. We'll see this throughout this book.
There are reasons for defining callable objects; it is a tidy way to provide namespace
for closely-related functions, and it supports a pleasant level of configurability.


We'll look at a common design pattern that works well with immutable objects: the
wrapper() function. A list of tuples is a fairly common data structure. We will often
process this list of tuples in one of the two following ways:



  • Using Higher-order Functions: As shown earlier, we provided lambda as
    an argument to the max() function: max(year_cheese, key=lambda yc:
    yc[1])

  • Using the Wrap-Process-Unwrap pattern: In a functional context, we should
    call this the unwrap(process(wrap(structure))) pattern

Free download pdf