Get started with functional programming in Python

Start writing shorter and less bug-prone Python code.

It is hard to get a consistent opinion on just what functional programming is, even from functional programmers themselves. A story about elephants and blind men seems apropos here. Usually we can contrast functional programming with “imperative programming” (what you do in languages like C, Pascal, C++, Java, Perl, Awk, TCL, and most others, at least for the most part). Functional programming is not object-oriented programming (OOP), although some languages are both. And it is not Logic Programming (e.g., Prolog).

I would roughly characterize functional programming as having at least several of the following characteristics:

  • Functions are first class (objects). That is, everything you can do with “data” can be done with functions themselves (such as passing a function to another function). Moreover, much functional programming utilizes “higher order” functions (in other words, functions that operate on functions that operate on functions).
  • Functional languages eschew side effects. This excludes the almost ubiquitous pattern in imperative languages of assigning first one, then another value to the same variable to track the program state.
  • In functional programming we focus not on constructing a data collection but rather on describing “what” that data collection consists of. When one simply thinks, “Here’s some data, what do I need to do with it?” rather than the mechanism of constructing the data, more direct reasoning is often possible.

Functional programming often makes for more rapidly developed, shorter, and less bug-prone code. Moreover, high theorists of computer science, logic, and math find it a lot easier to prove formal properties of functional languages and programs than of imperative languages and programs.

Python is most definitely not a “pure functional programming language”; side effects are widespread in most Python programs; variables are frequently rebound, mutable data collections often change contents, and I/O is freely interleaved with computation. However, Python is a multi-paradigm language that makes functional programming easy to do when desired, and easy to mix with other programming styles.

Many programs in Python can benefit from developing them in a more functional style. Functional Programming in Python provides readers with an excellent introduction to how to write Python in a more functional style, and when doing so make projects easier to create and maintain.

tags: , ,