Navigation

In this document, we’ll take a tour of Python’s features suitable for
implementing programs in a functional style. After an introduction to the
concepts of functional programming, we’ll look at language features such as
iterators and generators and relevant library modules such as
itertools and functools.

This section explains the basic concept of functional programming; if
you’re just interested in learning about Python language features,
skip to the next section on Iterators.

Programming languages support decomposing problems in several different ways:

Most programming languages are procedural: programs are lists of
instructions that tell the computer what to do with the program’s input. C,
Pascal, and even Unix shells are procedural languages.

In declarative languages, you write a specification that describes the
problem to be solved, and the language implementation figures out how to
perform the computation efficiently. SQL is the declarative language you’re
most likely to be familiar with; a SQL query describes the data set you want
to retrieve, and the SQL engine decides whether to scan tables or use indexes,
which subclauses should be performed first, etc.

Object-oriented programs manipulate collections of objects. Objects have
internal state and support methods that query or modify this internal state in
some way. Smalltalk and Java are object-oriented languages. C++ and Python
are languages that support object-oriented programming, but don’t force the
use of object-oriented features.

Functional programming decomposes a problem into a set of functions.
Ideally, functions only take inputs and produce outputs, and don’t have any
internal state that affects the output produced for a given input. Well-known
functional languages include the ML family (Standard ML, OCaml, and other
variants) and Haskell.

The designers of some computer languages choose to emphasize one
particular approach to programming. This often makes it difficult to
write programs that use a different approach. Other languages are
multi-paradigm languages that support several different approaches.
Lisp, C++, and Python are multi-paradigm; you can write programs or
libraries that are largely procedural, object-oriented, or functional
in all of these languages. In a large program, different sections
might be written using different approaches; the GUI might be
object-oriented while the processing logic is procedural or
functional, for example.

In a functional program, input flows through a set of functions. Each function
operates on its input and produces some output. Functional style discourages
functions with side effects that modify internal state or make other changes
that aren’t visible in the function’s return value. Functions that have no side
effects at all are called purely functional. Avoiding side effects means
not using data structures that get updated as a program runs; every function’s
output must only depend on its input.

Some languages are very strict about purity and don’t even have assignment
statements such as a=3 or c=a+b, but it’s difficult to avoid all
side effects. Printing to the screen or writing to a disk file are side
effects, for example. For example, in Python a call to the print() or
time.sleep() function both return no useful value; they’re only called for
their side effects of sending some text to the screen or pausing execution for a
second.

Python programs written in functional style usually won’t go to the extreme of
avoiding all I/O or all assignments; instead, they’ll provide a
functional-appearing interface but will use non-functional features internally.
For example, the implementation of a function will still use assignments to
local variables, but won’t modify global variables or have other side effects.

Functional programming can be considered the opposite of object-oriented
programming. Objects are little capsules containing some internal state along
with a collection of method calls that let you modify this state, and programs
consist of making the right set of state changes. Functional programming wants
to avoid state changes as much as possible and works with data flowing between
functions. In Python you might combine the two approaches by writing functions
that take and return instances representing objects in your application (e-mail
messages, transactions, etc.).

Functional design may seem like an odd constraint to work under. Why should you
avoid objects and side effects? There are theoretical and practical advantages
to the functional style:

A theoretical benefit is that it’s easier to construct a mathematical proof that
a functional program is correct.

For a long time researchers have been interested in finding ways to
mathematically prove programs correct. This is different from testing a program
on numerous inputs and concluding that its output is usually correct, or reading
a program’s source code and concluding that the code looks right; the goal is
instead a rigorous proof that a program produces the right result for all
possible inputs.

The technique used to prove programs correct is to write down invariants,
properties of the input data and of the program’s variables that are always
true. For each line of code, you then show that if invariants X and Y are true
before the line is executed, the slightly different invariants X’ and Y’ are
true after the line is executed. This continues until you reach the end of
the program, at which point the invariants should match the desired conditions
on the program’s output.

Functional programming’s avoidance of assignments arose because assignments are
difficult to handle with this technique; assignments can break invariants that
were true before the assignment without producing any new invariants that can be
propagated onward.

Unfortunately, proving programs correct is largely impractical and not relevant
to Python software. Even trivial programs require proofs that are several pages
long; the proof of correctness for a moderately complicated program would be
enormous, and few or none of the programs you use daily (the Python interpreter,
your XML parser, your web browser) could be proven correct. Even if you wrote
down or generated a proof, there would then be the question of verifying the
proof; maybe there’s an error in it, and you wrongly believe you’ve proved the
program correct.

A more practical benefit of functional programming is that it forces you to
break apart your problem into small pieces. Programs are more modular as a
result. It’s easier to specify and write a small function that does one thing
than a large function that performs a complicated transformation. Small
functions are also easier to read and to check for errors.

Debugging is simplified because functions are generally small and clearly
specified. When a program doesn’t work, each function is an interface point
where you can check that the data are correct. You can look at the intermediate
inputs and outputs to quickly isolate the function that’s responsible for a bug.

Testing is easier because each function is a potential subject for a unit test.
Functions don’t depend on system state that needs to be replicated before
running a test; instead you only have to synthesize the right input and then
check that the output matches expectations.

As you work on a functional-style program, you’ll write a number of functions
with varying inputs and outputs. Some of these functions will be unavoidably
specialized to a particular application, but others will be useful in a wide
variety of programs. For example, a function that takes a directory path and
returns all the XML files in the directory, or a function that takes a filename
and returns its contents, can be applied to many different situations.

Over time you’ll form a personal library of utilities. Often you’ll assemble
new programs by arranging existing functions in a new configuration and writing
a few functions specialized for the current task.

I’ll start by looking at a Python language feature that’s an important
foundation for writing functional-style programs: iterators.

An iterator is an object representing a stream of data; this object returns the
data one element at a time. A Python iterator must support a method called
__next__() that takes no arguments and always returns the next
element of the stream. If there are no more elements in the stream,
__next__() must raise the StopIteration exception.
Iterators don’t have to be finite, though; it’s perfectly reasonable to write
an iterator that produces an infinite stream of data.

The built-in iter() function takes an arbitrary object and tries to return
an iterator that will return the object’s contents or elements, raising
TypeError if the object doesn’t support iteration. Several of Python’s
built-in data types support iteration, the most common being lists and
dictionaries. An object is called iterable if you can get an iterator
for it.

Python expects iterable objects in several different contexts, the most
important being the for statement. In the statement forXinY,
Y must be an iterator or some object for which iter() can create an
iterator. These two statements are equivalent:

foriiniter(obj):print(i)foriinobj:print(i)

Iterators can be materialized as lists or tuples by using the list() or
tuple() constructor functions:

>>> L=[1,2,3]>>> iterator=iter(L)>>> t=tuple(iterator)>>> t(1, 2, 3)

Sequence unpacking also supports iterators: if you know an iterator will return
N elements, you can unpack them into an N-tuple:

>>> L=[1,2,3]>>> iterator=iter(L)>>> a,b,c=iterator>>> a,b,c(1, 2, 3)

Built-in functions such as max() and min() can take a single
iterator argument and will return the largest or smallest element. The "in"
and "notin" operators also support iterators: Xiniterator is true if
X is found in the stream returned by the iterator. You’ll run into obvious
problems if the iterator is infinite; max(), min()
will never return, and if the element X never appears in the stream, the
"in" and "notin" operators won’t return either.

Note that you can only go forward in an iterator; there’s no way to get the
previous element, reset the iterator, or make a copy of it. Iterator objects
can optionally provide these additional capabilities, but the iterator protocol
only specifies the __next__() method. Functions may therefore
consume all of the iterator’s output, and if you need to do something different
with the same stream, you’ll have to create a new iterator.

Note that the order is essentially random, because it’s based on the hash
ordering of the objects in the dictionary.

Applying iter() to a dictionary always loops over the keys, but
dictionaries have methods that return other iterators. If you want to iterate
over values or key/value pairs, you can explicitly call the
values() or items() methods to get an appropriate
iterator.

The dict() constructor can accept an iterator that returns a finite stream
of (key,value) tuples:

Two common operations on an iterator’s output are 1) performing some operation
for every element, 2) selecting a subset of elements that meet some condition.
For example, given a list of strings, you might want to strip off trailing
whitespace from each line or extract all the strings containing a given
substring.

List comprehensions and generator expressions (short form: “listcomps” and
“genexps”) are a concise notation for such operations, borrowed from the
functional programming language Haskell (https://www.haskell.org/). You can strip
all the whitespace from a stream of strings with the following code:

With a list comprehension, you get back a Python list; stripped_list is a
list containing the resulting lines, not an iterator. Generator expressions
return an iterator that computes the values as necessary, not needing to
materialize all the values at once. This means that list comprehensions aren’t
useful if you’re working with iterators that return an infinite stream or a very
large amount of data. Generator expressions are preferable in these situations.

Generator expressions are surrounded by parentheses (“()”) and list
comprehensions are surrounded by square brackets (“[]”). Generator expressions
have the form:

Again, for a list comprehension only the outside brackets are different (square
brackets instead of parentheses).

The elements of the generated output will be the successive values of
expression. The if clauses are all optional; if present, expression
is only evaluated and added to the result when condition is true.

Generator expressions always have to be written inside parentheses, but the
parentheses signalling a function call also count. If you want to create an
iterator that will be immediately passed to a function you can write:

obj_total=sum(obj.countforobjinlist_all_objects())

The for...in clauses contain the sequences to be iterated over. The
sequences do not have to be the same length, because they are iterated over from
left to right, not in parallel. For each element in sequence1,
sequence2 is looped over from the beginning. sequence3 is then looped
over for each resulting pair of elements from sequence1 and sequence2.

To put it another way, a list comprehension or generator expression is
equivalent to the following Python code:

forexpr1insequence1:ifnot(condition1):continue# Skip this elementforexpr2insequence2:ifnot(condition2):continue# Skip this element...forexprNinsequenceN:ifnot(conditionN):continue# Skip this element# Output the value of# the expression.

This means that when there are multiple for...in clauses but no if
clauses, the length of the resulting output will be equal to the product of the
lengths of all the sequences. If you have two lists of length 3, the output
list is 9 elements long:

To avoid introducing an ambiguity into Python’s grammar, if expression is
creating a tuple, it must be surrounded with parentheses. The first list
comprehension below is a syntax error, while the second one is correct:

Generators are a special class of functions that simplify the task of writing
iterators. Regular functions compute a value and return it, but generators
return an iterator that returns a stream of values.

You’re doubtless familiar with how regular function calls work in Python or C.
When you call a function, it gets a private namespace where its local variables
are created. When the function reaches a return statement, the local
variables are destroyed and the value is returned to the caller. A later call
to the same function creates a new private namespace and a fresh set of local
variables. But, what if the local variables weren’t thrown away on exiting a
function? What if you could later resume the function where it left off? This
is what generators provide; they can be thought of as resumable functions.

Here’s the simplest example of a generator function:

>>> defgenerate_ints(N):... foriinrange(N):... yieldi

Any function containing a yield keyword is a generator function;
this is detected by Python’s bytecode compiler which compiles the
function specially as a result.

When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol. On executing
the yield expression, the generator outputs the value of i, similar to a
return statement. The big difference between yield and a return
statement is that on reaching a yield the generator’s state of execution is
suspended and local variables are preserved. On the next call to the
generator’s __next__() method, the function will resume
executing.

You could equally write foriingenerate_ints(5), or a,b,c=generate_ints(3).

Inside a generator function, returnvalue causes StopIteration(value)
to be raised from the __next__() method. Once this happens, or
the bottom of the function is reached, the procession of values ends and the
generator cannot yield any further values.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables. For
example, returning a list of integers could be done by setting self.count to
0, and having the __next__() method increment self.count and
return it.
However, for a moderately complicated generator, writing a corresponding class
can be much messier.

The test suite included with Python’s library,
Lib/test/test_generators.py, contains
a number of more interesting examples. Here’s one generator that implements an
in-order traversal of a tree using generators recursively.

# A recursive generator that generates Tree leaves in in-order.definorder(t):ift:forxininorder(t.left):yieldxyieldt.labelforxininorder(t.right):yieldx

Two other examples in test_generators.py produce solutions for the N-Queens
problem (placing N queens on an NxN chess board so that no queen threatens
another) and the Knight’s Tour (finding a route that takes a knight to every
square of an NxN chessboard without visiting any square twice).

In Python 2.4 and earlier, generators only produced output. Once a generator’s
code was invoked to create an iterator, there was no way to pass any new
information into the function when its execution is resumed. You could hack
together this ability by making the generator look at a global variable or by
passing in some mutable object that callers then modify, but these approaches
are messy.

In Python 2.5 there’s a simple way to pass values into a generator.
yield became an expression, returning a value that can be assigned to
a variable or otherwise operated on:

val=(yieldi)

I recommend that you always put parentheses around a yield expression
when you’re doing something with the returned value, as in the above example.
The parentheses aren’t always necessary, but it’s easier to always add them
instead of having to remember when they’re needed.

(PEP 342 explains the exact rules, which are that a yield-expression must
always be parenthesized except when it occurs at the top-level expression on the
right-hand side of an assignment. This means you can write val=yieldi
but have to use parentheses when there’s an operation, as in val=(yieldi)+12.)

Values are sent into a generator by calling its send(value) method. This method resumes the generator’s code and the
yield expression returns the specified value. If the regular
__next__() method is called, the yield returns None.

Here’s a simple counter that increments by 1 and allows changing the value of
the internal counter.

Because yield will often be returning None, you should always check for
this case. Don’t just use its value in expressions unless you’re sure that the
send() method will be the only method used to resume your
generator function.

close() raises a GeneratorExit exception inside the
generator to terminate the iteration. On receiving this exception, the
generator’s code must either raise GeneratorExit or
StopIteration; catching the exception and doing anything else is
illegal and will trigger a RuntimeError. close()
will also be called by Python’s garbage collector when the generator is
garbage-collected.

If you need to run cleanup code when a GeneratorExit occurs, I suggest
using a try:...finally: suite instead of catching GeneratorExit.

The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.

Generators also become coroutines, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a return statement), but coroutines can be entered, exited,
and resumed at many different points (the yield statements).

filter(predicate,iter) returns an iterator over all the
sequence elements that meet a certain condition, and is similarly duplicated by
list comprehensions. A predicate is a function that returns the truth
value of some condition; for use with filter(), the predicate must take a
single value.

>>> defis_even(x):... return(x%2)==0

>>> list(filter(is_even,range(10)))[0, 2, 4, 6, 8]

This can also be written as a list comprehension:

>>> list(xforxinrange(10)ifis_even(x))[0, 2, 4, 6, 8]

enumerate(iter) counts off the elements in the iterable,
returning 2-tuples containing the count and each element.

enumerate() is often used when looping through a list and recording the
indexes at which certain conditions are met:

f=open('data.txt','r')fori,lineinenumerate(f):ifline.strip()=='':print('Blank line at line #%i'%i)

sorted(iterable,key=None,reverse=False) collects all the
elements of the iterable into a list, sorts the list, and returns the sorted
result. The key and reverse arguments are passed through to the
constructed list’s sort() method.

The any(iter) and all(iter) built-ins look at the
truth values of an iterable’s contents. any() returns True if any element
in the iterable is a true value, and all() returns True if all of the
elements are true values:

It doesn’t construct an in-memory list and exhaust all the input iterators
before returning; instead tuples are constructed and returned only if they’re
requested. (The technical term for this behaviour is lazy evaluation.)

This iterator is intended to be used with iterables that are all of the same
length. If the iterables are of different lengths, the resulting stream will be
the same length as the shortest iterable.

zip(['a','b'],(1,2,3))=>('a',1),('b',2)

You should avoid doing this, though, because an element may be taken from the
longer iterators and discarded. This means you can’t go on to use the iterators
further because you risk skipping a discarded element.

itertools.cycle(iter) saves a copy of the contents of
a provided iterable and returns a new iterator that returns its elements from
first to last. The new iterator will repeat these elements infinitely.

itertools.chain(iterA,iterB,...) takes an arbitrary
number of iterables as input, and returns all the elements of the first
iterator, then all the elements of the second, and so on, until all of the
iterables have been exhausted.

itertools.chain(['a','b','c'],(1,2,3))=>a,b,c,1,2,3

itertools.islice(iter,[start],stop,[step]) returns
a stream that’s a slice of the iterator. With a single stop argument, it
will return the first stop elements. If you supply a starting index, you’ll
get stop-start elements, and if you supply a value for step, elements
will be skipped accordingly. Unlike Python’s string and list slicing, you can’t
use negative values for start, stop, or step.

itertools.tee(iter,[n]) replicates an iterator; it
returns n independent iterators that will all return the contents of the
source iterator.
If you don’t supply a value for n, the default is 2. Replicating iterators
requires saving some of the contents of the source iterator, so this can consume
significant memory if the iterator is large and one of the new iterators is
consumed more than the others.

The elements within each tuple remain in the same order as
iterable returned them. For example, the number 1 is always before
2, 3, 4, or 5 in the examples above. A similar function,
itertools.permutations(iterable,r=None),
removes this constraint on the order, returning all possible
arrangements of length r:

The identical tuple ('a','a','b') occurs twice, but the two ‘a’
strings came from different positions.

The itertools.combinations_with_replacement(iterable,r)
function relaxes a different constraint: elements can be repeated
within a single tuple. Conceptually an element is selected for the
first position of each tuple and then is replaced before the second
element is selected.

The last function I’ll discuss, itertools.groupby(iter,key_func=None), is the most complicated. key_func(elem) is a function
that can compute a key value for each element returned by the iterable. If you
don’t supply a key function, the key is simply each element itself.

groupby() collects all the consecutive elements from the
underlying iterable that have the same key value, and returns a stream of
2-tuples containing a key value and an iterator for the elements with that key.

groupby() assumes that the underlying iterable’s contents will
already be sorted based on the key. Note that the returned iterators also use
the underlying iterable, so you have to consume the results of iterator-1 before
requesting iterator-2 and its corresponding key.

The functools module in Python 2.5 contains some higher-order functions.
A higher-order function takes one or more functions as input and returns a
new function. The most useful tool in this module is the
functools.partial() function.

For programs written in a functional style, you’ll sometimes want to construct
variants of existing functions that have some of the parameters filled in.
Consider a Python function f(a,b,c); you may wish to create a new function
g(b,c) that’s equivalent to f(1,b,c); you’re filling in a value for
one of f()‘s parameters. This is called “partial function application”.

The constructor for partial() takes the arguments
(function,arg1,arg2,...,kwarg1=value1,kwarg2=value2). The resulting
object is callable, so you can just call it to invoke function with the
filled-in arguments.

Here’s a small but realistic example:

importfunctoolsdeflog(message,subsystem):"""Write the contents of 'message' to the specified subsystem."""print('%s: %s'%(subsystem,message))...server_log=functools.partial(log,subsystem='server')server_log('Unable to open socket')

functools.reduce(func,iter,[initial_value])
cumulatively performs an operation on all the iterable’s elements and,
therefore, can’t be applied to infinite iterables. func must be a function
that takes two elements and returns a single value. functools.reduce()
takes the first two elements A and B returned by the iterator and calculates
func(A,B). It then requests the third element, C, calculates
func(func(A,B),C), combines this result with the fourth element returned,
and continues until the iterable is exhausted. If the iterable returns no
values at all, a TypeError exception is raised. If the initial value is
supplied, it’s used as a starting point and func(initial_value,A) is the
first calculation.

importfunctools# Instead of:product=functools.reduce(operator.mul,[1,2,3],1)# You can write:product=1foriin[1,2,3]:product*=i

A related function is itertools.accumulate(iterable, func=operator.add) <itertools.accumulate.
It performs the same calculation, but instead of returning only the
final result, accumulate() returns an iterator that also yields
each partial result:

The operator module was mentioned earlier. It contains a set of
functions corresponding to Python’s operators. These functions are often useful
in functional-style code because they save you from writing trivial functions
that perform a single operation.

If the function you need doesn’t exist, you need to write it. One way to write
small functions is to use the lambda statement. lambda takes a
number of parameters and an expression combining these parameters, and creates
an anonymous function that returns the value of the expression:

adder=lambdax,y:x+yprint_assign=lambdaname,value:name+'='+str(value)

An alternative is to just use the def statement and define a function in the
usual way:

Which alternative is preferable? That’s a style question; my usual course is to
avoid using lambda.

One reason for my preference is that lambda is quite limited in the
functions it can define. The result has to be computable as a single
expression, which means you can’t have multiway if...elif...else
comparisons or try...except statements. If you try to do too much in a
lambda statement, you’ll end up with an overly complicated expression that’s
hard to read. Quick, what’s the following code doing?

Structure and Interpretation of Computer Programs, by Harold Abelson and
Gerald Jay Sussman with Julie Sussman. Full text at
https://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
chapters 2 and 3 discuss the use of sequences and streams to organize the data
flow inside a program. The book uses Scheme for its examples, but many of the
design approaches described in these chapters are applicable to functional-style
Python code.

http://gnosis.cx/TPiP/: The first chapter of David Mertz’s book
Text Processing in Python discusses functional programming
for text processing, in the section titled “Utilizing Higher-Order Functions in
Text Processing”.

Mertz also wrote a 3-part series of articles on functional programming
for IBM’s DeveloperWorks site; see
part 1,
part 2, and
part 3,