Howto Functional
Howto Functional
Release 2.7.10
Contents
1
Introduction
1.1 Formal provability . . . . . .
1.2 Modularity . . . . . . . . . .
1.3 Ease of debugging and testing
1.4 Composability . . . . . . . . .
.
.
.
.
2
3
3
3
3
Iterators
2.1 Data Types That Support Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
5
Generators
4.1 Passing values into a generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7
8
Built-in functions
10
12
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13
13
14
15
15
16
16
17
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10 References
10.1 General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.2 Python-specific . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10.3 Python documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17
17
17
17
Index
18
Author A. M. Kuchling
Release 0.31
In this document, well take a tour of Pythons features suitable for implementing programs in a functional style.
After an introduction to the concepts of functional programming, well look at language features such as iterators
and generators and relevant library modules such as itertools and functools.
1 Introduction
This section explains the basic concept of functional programming; if youre just interested in learning about
Python language features, skip to the next section.
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 programs 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
youre 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 dont force the use of objectoriented features.
Functional programming decomposes a problem into a set of functions. Ideally, functions only take inputs
and produce outputs, and dont 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 arent visible in the functions 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 functions output must only depend on its input.
Some languages are very strict about purity and dont even have assignment statements such as a=3 or c = a
+ b, but its 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 print statement or a time.sleep(1) both return no useful value; theyre
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 wont go to the extreme of avoiding all I/O or all assignments;
instead, theyll 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 wont 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:
Formal provability.
Modularity.
Composability.
Ease of debugging and testing.
1.2 Modularity
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. Its 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.
1.4 Composability
As you work on a functional-style program, youll 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 youll form a personal library of utilities. Often youll assemble new programs by arranging existing
functions in a new configuration and writing a few functions specialized for the current task.
2 Iterators
Ill start by looking at a Python language feature thats 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 dont have to be finite, though; its 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 objects
contents or elements, raising TypeError if the object doesnt support iteration. Several of Pythons built-in data
types support iteration, the most common being lists and dictionaries. An object is called an iterable object if you
can get an iterator for it.
You can experiment with the iteration interface manually:
>>> L = [1,2,3]
>>> it = iter(L)
>>> print it
<...iterator object at ...>
>>> it.next()
1
>>> it.next()
2
>>> it.next()
3
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
>>>
Python expects iterable objects in several different contexts, the most important being the for statement. In the
statement for X in Y, Y must be an iterator or some object for which iter() can create an iterator. These
two statements are equivalent:
for i in iter(obj):
print i
for i in obj:
print i
Iterators can be materialized as lists or tuples by using the list() or tuple() constructor functions:
>>>
>>>
>>>
>>>
(1,
L = [1,2,3]
iterator = iter(L)
t = tuple(iterator)
t
2, 3)
Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them
into an N-tuple:
>>>
>>>
>>>
>>>
(1,
L = [1,2,3]
iterator = iter(L)
a,b,c = iterator
a,b,c
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 "not in" operators also support iterators: X in iterator is true if X is
found in the stream returned by the iterator. Youll 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 "not in" operators
wont return either.
Note that you can only go forward in an iterator; theres 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 iterators output, and if you need
to do something different with the same stream, youll have to create a new iterator.
Note that the order is essentially random, because its 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 keys, values, or key/value pairs, you can explicitly call the iterkeys(),
itervalues(), or iteritems() methods to get an appropriate iterator.
The dict() constructor can accept an iterator that returns a finite stream of (key, value) tuples:
>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
{'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
Files also support iteration by calling the readline() method until there are no more lines in the file. This
means you can read each line of a file like this:
for line in file:
# do something for each line
...
Sets can take their contents from an iterable and let you iterate over the sets elements:
\n', ...]
'abc'
(1,2,3)
for x in seq1 for y in seq2]
('a', 2), ('a', 3),
('b', 2), ('b', 3),
('c', 2), ('c', 3)]
To avoid introducing an ambiguity into Pythons 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:
#
[
#
[
Syntax error
x,y for x in seq1 for y in seq2]
Correct
(x,y) for x in seq1 for y in seq2]
4 Generators
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.
Youre 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 werent 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.
Heres the simplest example of a generator function:
def generate_ints(N):
for i in range(N):
yield i
Any function containing a yield keyword is a generator function; this is detected by Pythons bytecode compiler
which compiles the function specially as a result.
When you call a generator function, it doesnt 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 generators state of execution is suspended and local variables are preserved. On the next call to the generators
.next() method, the function will resume executing.
Heres a sample usage of the generate_ints() generator:
(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 =
yield i but have to use parentheses when theres an operation, as in val = (yield i) + 12.)
Values are sent into a generator by calling its send(value) method. This method resumes the generators code
and the yield expression returns the specified value. If the regular next() method is called, the yield returns
None.
Heres a simple counter that increments by 1 and allows changing the value of the internal counter.
def counter (maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
And heres an example of changing the counter:
>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
File "t.py", line 15, in ?
print it.next()
StopIteration
Because yield will often be returning None, you should always check for this case. Dont just use its value in
expressions unless youre sure that the send() method will be the only method used to resume your generator
function.
In addition to send(), there are two other new methods on generators:
throw(type, value=None, traceback=None) is used to raise an exception inside the generator;
the exception is raised by the yield expression where the generators execution is paused.
close() raises a GeneratorExit exception inside the generator to terminate the iteration. On receiving this exception, the generators 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 Pythons 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).
5 Built-in functions
Lets look in more detail at built-in functions often used with iterators.
Two of Pythons built-in functions, map() and filter(), are somewhat obsolete; they duplicate the features
of list comprehensions but return actual lists instead of iterators.
map(f, iterA, iterB, ...) returns a list containing f(iterA[0], iterB[0]), f(iterA[1],
iterB[1]), f(iterA[2], iterB[2]), ....
>>> def upper(s):
...
return s.upper()
>>> map(upper, ['sentence', 'fragment'])
['SENTENCE', 'FRAGMENT']
>>> [upper(s) for s in ['sentence', 'fragment']]
['SENTENCE', 'FRAGMENT']
As shown above, you can achieve the same effect with a list comprehension. The itertools.imap() function
does the same thing but can handle infinite iterators; itll be discussed later, in the section on the itertools
module.
filter(predicate, iter) returns a list that contains 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.
>>> def is_even(x):
...
return (x % 2) == 0
>>> filter(is_even, range(10))
[0, 2, 4, 6, 8]
This can also be written as a list comprehension:
>>> [x for x in range(10) if is_even(x)]
[0, 2, 4, 6, 8]
filter() also has a counterpart in the itertools module, itertools.ifilter(), that returns an iterator and can therefore handle infinite sequences just as itertools.imap() can.
reduce(func, iter, [initial_value]) doesnt have a counterpart in the itertools module because it cumulatively performs an operation on all the iterables elements and therefore cant be applied to infinite
iterables. func must be a function that takes two elements and returns a single value. 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, its used as a starting point and func(initial_value, A) is the first calculation.
>>> import operator
>>> reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> reduce(operator.concat, [])
Traceback (most recent call last):
...
TypeError: reduce() of empty sequence with no initial value
>>> reduce(operator.mul, [1,2,3], 1)
6
>>> reduce(operator.mul, [], 1)
1
If you use operator.add() with reduce(), youll add up all the elements of the iterable. This case is so
common that theres a special built-in called sum() to compute it:
enumerate() is often used when looping through a list and recording the indexes at which certain conditions
are met:
f = open('data.txt', 'r')
for i, line in enumerate(f):
if line.strip() == '':
print 'Blank line at line #%i' % i
sorted(iterable, [cmp=None], [key=None], [reverse=False]) collects all the elements of
the iterable into a list, sorts the list, and returns the sorted result. The cmp, key, and reverse arguments are
passed through to the constructed lists .sort() method.
>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the Python wiki at
https://wiki.python.org/moin/HowTo/Sorting.)
The any(iter) and all(iter) built-ins look at the truth values of an iterables 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:
>>> any([0,1,0])
True
>>> any([0,0,0])
False
>>> any([1,1,1])
True
>>> all([0,1,0])
False
>>> all([0,0,0])
False
>>> all([1,1,1])
True
Its similar to the built-in zip() function, but doesnt construct an in-memory list and exhaust all the input
iterators before returning; instead tuples are constructed and returned only if theyre 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.
itertools.izip(['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 cant go on to use the iterators further because you risk skipping a discarded element.
itertools.islice(iter, [start], stop, [step]) returns a stream thats a slice of the iterator.
With a single stop argument, it will return the first stop elements. If you supply a starting index, youll get
stop-start elements, and if you supply a value for step, elements will be skipped accordingly. Unlike
Pythons string and list slicing, you cant use negative values for start, stop, or step.
itertools.islice(range(10), 8) =>
0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
2, 4, 6
itertools.tee(iter, [n]) replicates an iterator; it returns n independent iterators that will all return the
contents of the source iterator. If you dont 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.
itertools.tee( itertools.count() ) =>
iterA, iterB
where iterA ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
and
iterB ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
f(iterA[0],
where
iterator-1 =>
('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
groupby() assumes that the underlying iterables 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.
10 References
10.1 General
Structure and Interpretation of Computer Programs, by Harold Abelson and Gerald Jay Sussman with Julie
Sussman. Full text at http://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://www.defmacro.org/ramblings/fp.html: A general introduction to functional programming that uses Java
examples and has a lengthy historical introduction.
http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry describing functional programming.
http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
10.2 Python-specific
http://gnosis.cx/TPiP/: The first chapter of David Mertzs 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 IBMs DeveloperWorks site; see
part 1, part 2, and part 3,
Index
P
Python Enhancement Proposals
PEP 289, 17
PEP 342, 17
18