Functional Python Programming

(Wang) #1
Chapter 2

There isn't a trivial way to guarantee a Python function is free from side effects. It is
easy to carelessly break the pure function rule. If we ever want to worry about our
ability to follow this rule, we could write a function that uses the dis module to scan
a given function's code.co_code compiled code for global references. It could
report on use of internal closures, and the code.co_freevars tuple method as
well. This is a rather complex solution to a rare problem; we won't pursue it further.


A Python lambda is a pure function. While this isn't a highly recommended style,
it's certainly possible to create pure functions via lambda values.


Here's a function created by assigning lambda to a variable:





mersenne = lambda x: 2**x-1








mersenne(17)





131071


We created a pure function using lambda and assigned this to the variable mersenne.
This is a callable object with a single argument value that returns a single value.
Because lambda's can't have assignment statements, they're always pure functions
and suitable for functional programming.


Higher-order functions


We can achieve expressive, succinct programs using higher-order functions.
These are functions that accept a function as an argument or return a function as
a value. We can use higher-order functions as a way to create composite functions
from simpler functions.


Consider the Python max() function. We can provide a function as an argument
and modify how the max() function behaves.


Here's some data we might want to process:





year_cheese = [(2000, 29.87), (2001, 30.12), (2002, 30.6), (2003,
30.66),(2004, 31.33), (2005, 32.62), (2006, 32.73), (2007, 33.5),
(2008, 32.84), (2009, 33.02), (2010, 32.92)]





We can apply the max() function as follows:





max(year_cheese)





(2010, 32.92)


The default behavior is to simply compare each tuple in the sequence. This will
return the tuple with the largest value on position 0.

Free download pdf