Functional Python Programming

(Wang) #1
Chapter 5

Using Python for functional programming means walking on a knife edge between
purely functional programming and imperative programming. We need to identify
and isolate the places where we must resort to imperative Python code because there
isn't a purely functional alternative available.


We're obligated to write generator functions when we need statement features
of Python. Features like the following aren't available in generator expressions:



  • A with context to work with external resources. We'll look at this in Chapter
    6 , Recursions and Reductions, where we address file parsing.

  • A while statement to iterate somewhat more flexibly than a for statement.
    The example of this is shown previously in the Flattening data while mapping
    section.

  • A break or return statement to implement a search that terminates
    a loop early.

  • The try-except construct to handle exceptions.

  • An internal function definition. We've looked at this in several examples in
    Chapter 1, Introducing Functional Programming and Chapter 2, Introducing Some
    Functional Features. We'll also revisit it in Chapter 6, Recursions and Reductions.

  • A really complex if-elif sequence. Trying to express more than
    one alternatives via if-else conditional expressions can become
    complex-looking.

  • At the edge of the envelope, we have less-used features of Python such as
    for-else, while-else, try-else, and try-else-finally. These are all
    statement-level features that aren't available in generator expressions.


The break statement is most commonly used to end processing of a collection early.
We can end processing after the first item that satisfies some criteria. This is a version
of the any() function we're looking at to find the existence of a value with a given
property. We can also end after processing some larger numbers of items, but not all
of them.


Finding a single value can be expressed succinctly as min(some-big-expression)
or max(something big). In these cases, we're committed to examining all of the
values to assure that we've properly found the minimum or the maximum.


In a few cases, we can stand to have a first(function, collection) function
where the first value that is True is sufficient. We'd like the processing to terminate
as early as possible, saving needless calculation.

Free download pdf