4.17 Functional-Style Programming

  • Python offers “functional-style” features that help you write code which is less likely to contain errors, more concise and easier to read, debug and modify.
  • The chart below lists most of Python’s key functional-style programming capabilities and shows in parentheses the chapters in which we initially cover many of them.
Functional-style programming topics
avoiding side effects (4)
closures
declarative programming (4)
decorators (10)
dictionary comprehensions (6)
filter/map/reduce (5)
functools module
generator expressions (5)
generator functions
higher-order functions (5)
immutability (4)
internal iteration (4)
iterators (3)
itertools module (16)
lambda expressions (5)
lazy evaluation (5)
list comprehensions (5)
operator module (5, 11, 16)
pure functions (4)
range function (3, 4)
reductions (3, 5)
set comprehensions (6)

What vs. How

  • Functional-style programming lets you simply say what you want to do.
  • Typically, library code handles the how for you.
  • Can eliminate many errors.
  • Functional-style programming emphasizes immutability.
  • Python’s for statement and range function hide most counter-controlled iteration details.
    • You specify what values range should produce and the variable that should receive each value as it’s produced.
    • Function range knows how to produce those values.
    • The for statement knows how to get each value from range and how to stop iterating when there are no more values.
  • Specifying what, but not how, is an important aspect of internal iteration—a key functional-style programming concept.
  • Stating what you want done rather than programming how to do it is known as declarative programming.

Pure Functions

  • A pure function’s result depends only on the argument(s) you pass to it.
  • Given a particular argument (or arguments), a pure function always produces the same result.
  • A pure function does not have side effects.
In [1]:
values = [1, 2, 3]
In [2]:
sum(values)
Out[2]:
6
In [3]:
sum(values)  # same call always returns same result
Out[3]:
6
In [4]:
values
Out[4]:
[1, 2, 3]

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 4 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.