Chapter 4. Functional Programming – Readability Versus Brevity

Python is one of the few (or at least the earliest) nonfunctional languages to incorporate functional features. While Guido van Rossum has tried to remove some of them a few times, they have become ingrained in the Python community, and list comprehensions (dict and set comprehensions soon to follow) are widely used in all sorts of code. The most important thing about code shouldn't be how cool your reduce statement is or how you can fit the entire function in a single line with an incomprehensible list comprehension. Readability counts (once again, PEP20)!

This chapter will show you some of the cool tricks that functional programming in Python gives you, and it will explain some of the limitations of Python's implementation. While we will try to steer clear of lambda calculus (λ-calculus) as much as possible, the Y combinator will be discussed briefly.

The last few paragraphs will list (and explain) the usage of the functools and itertools libraries. If you are familiar with these libraries, feel free to skip them, but note that some of these will be used heavily in the later chapters about decorators (Chapter 5, Decorators – Enabling Code Reuse by Decorating), generators (Chapter 6, Generators and Coroutines – Infinity, One Step at a Time), and performance (Chapter 12, Performance – Tracking and Reducing Your Memory and CPU Usage).

These are the topics covered in this chapter:

  • The theory behind functional programming
  • list comprehensions
  • dict comprehensions
  • set comprehensions
  • lambda functions
  • functools (partial, and reduce)
  • itertools (accumulate, chain, dropwhile, starmap, and so on)

Functional programming

Functional programming is a paradigm that originates from the lambda calculus. Without diving too much into the lambda calculus (λ-calculus), this roughly means that computation is performed through the use of mathematical functions, which avoids mutable data and changing state of surroundings. The idea of a strictly functional language is that all function outputs are dependent only on the input and not on any external state. Since Python is not strictly a programming language, this doesn't necessarily hold true, but it is a good idea to adhere to this paradigm as mixing these can cause unforeseen bugs as discussed in Chapter 2, Pythonic Syntax, Common Pitfalls, and Style Guide.

Even outside of functional programming, this is a good idea. Keeping functions purely functional (relying only on the given input) makes code clearer, easier to understand, and better to test as there are less dependencies. Well-known examples can be found within the math module. These functions (sin, cos, pow, sqrt, and so on) have an input and an output that is strictly dependent on the input.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset