Python Functional Programming

Clinton Nguyen
2 min readDec 31, 2020

Demonstration

As a quarantined 14 year old in remote learning, I wanted to try something new with Python. I was doing some research on some new libraries to try out and I came across one called PyToolz. Essentially, this library allows you to do functional programming in Python without having to learn a functional language like Lisp or Haskell.

What is functional programming? It’s a way of programming that uses pure functions, functions that return the same outputs for the same inputs, to construct programs. Let’s look at the differences between conventional and functional programming. I’ll use Project Euler’s problem #1, which asks for the sum of all multiples of three and five below 1000.

def euler_p1():
sum = 0
for x in range(1000):
if x % 3 == 0 or x % 5 == 0:
sum += x
return sum

The snippet of code above is a conventional approach to the problem. We loop through numbers until 1,000 and check if they are multiples of three or five. If it meets this requirement, then it’s added to our sum variable.

from toolz.curried import *def euler_p1():    def multiple(x):
return x % 3 == 0 or x % 5 == 0
solution = pipe(1000, range, filter(multiple), sum)

This snippet of code above is a functional approach to the question. We put a value in the pipe, which is then followed by functions that modify the data. In this example, we pass in 1,000 and range since that’s what we want to work with. Afterwards, we use the filter() function from the PyToolz library, which will filter out values that aren’t multiples of three or five. Finally, since the question is asking for the sums of all these multiples, we pass in a sum function.

Although it may seem like an entirely new language, functional programming requires less thinking and planning than conventional programming. In addition, the end result is easier to read and understand.

References

PyToolz Documentation: https://toolz.readthedocs.io/en/latest/

Project Euler Problems: https://projecteuler.net/archives

Disclaimer

I started learning Python the summer of 2020, so my code isn’t going to be the cleanest or most efficient. I’m also quite new to functional programming, as I have a lot to learn. I’m writing these articles to hopefully learn more, share my learnings with others who are interested and improve my writing skills along the way. In the next few articles, I’ll go into more detail about functional programming terms. Thanks for reading.

--

--