blob: 4dea527938ef35d1371724585f740065b2cf75f9 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001********************************
2 Functional Programming HOWTO
3********************************
4
Christian Heimesfe337bf2008-03-23 21:54:12 +00005:Author: A. M. Kuchling
Christian Heimes0449f632007-12-15 01:27:15 +00006:Release: 0.31
Georg Brandl116aa622007-08-15 14:28:22 +00007
8(This is a first draft. Please send comments/error reports/suggestions to
Christian Heimes0449f632007-12-15 01:27:15 +00009amk@amk.ca.)
Georg Brandl116aa622007-08-15 14:28:22 +000010
11In this document, we'll take a tour of Python's features suitable for
12implementing programs in a functional style. After an introduction to the
13concepts of functional programming, we'll look at language features such as
Georg Brandl9afde1c2007-11-01 20:32:30 +000014:term:`iterator`\s and :term:`generator`\s and relevant library modules such as
15:mod:`itertools` and :mod:`functools`.
Georg Brandl116aa622007-08-15 14:28:22 +000016
17
18Introduction
19============
20
21This section explains the basic concept of functional programming; if you're
22just interested in learning about Python language features, skip to the next
23section.
24
25Programming languages support decomposing problems in several different ways:
26
27* Most programming languages are **procedural**: programs are lists of
28 instructions that tell the computer what to do with the program's input. C,
29 Pascal, and even Unix shells are procedural languages.
30
31* In **declarative** languages, you write a specification that describes the
32 problem to be solved, and the language implementation figures out how to
33 perform the computation efficiently. SQL is the declarative language you're
34 most likely to be familiar with; a SQL query describes the data set you want
35 to retrieve, and the SQL engine decides whether to scan tables or use indexes,
36 which subclauses should be performed first, etc.
37
38* **Object-oriented** programs manipulate collections of objects. Objects have
39 internal state and support methods that query or modify this internal state in
40 some way. Smalltalk and Java are object-oriented languages. C++ and Python
41 are languages that support object-oriented programming, but don't force the
42 use of object-oriented features.
43
44* **Functional** programming decomposes a problem into a set of functions.
45 Ideally, functions only take inputs and produce outputs, and don't have any
46 internal state that affects the output produced for a given input. Well-known
47 functional languages include the ML family (Standard ML, OCaml, and other
48 variants) and Haskell.
49
Christian Heimes0449f632007-12-15 01:27:15 +000050The designers of some computer languages choose to emphasize one
51particular approach to programming. This often makes it difficult to
52write programs that use a different approach. Other languages are
53multi-paradigm languages that support several different approaches.
54Lisp, C++, and Python are multi-paradigm; you can write programs or
55libraries that are largely procedural, object-oriented, or functional
56in all of these languages. In a large program, different sections
57might be written using different approaches; the GUI might be
58object-oriented while the processing logic is procedural or
59functional, for example.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61In a functional program, input flows through a set of functions. Each function
Christian Heimes0449f632007-12-15 01:27:15 +000062operates on its input and produces some output. Functional style discourages
Georg Brandl116aa622007-08-15 14:28:22 +000063functions with side effects that modify internal state or make other changes
64that aren't visible in the function's return value. Functions that have no side
65effects at all are called **purely functional**. Avoiding side effects means
66not using data structures that get updated as a program runs; every function's
67output must only depend on its input.
68
69Some languages are very strict about purity and don't even have assignment
70statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all
71side effects. Printing to the screen or writing to a disk file are side
Georg Brandl0df79792008-10-04 18:33:26 +000072effects, for example. For example, in Python a call to the :func:`print` or
73:func:`time.sleep` function both return no useful value; they're only called for
74their side effects of sending some text to the screen or pausing execution for a
Georg Brandl116aa622007-08-15 14:28:22 +000075second.
76
77Python programs written in functional style usually won't go to the extreme of
78avoiding all I/O or all assignments; instead, they'll provide a
79functional-appearing interface but will use non-functional features internally.
80For example, the implementation of a function will still use assignments to
81local variables, but won't modify global variables or have other side effects.
82
83Functional programming can be considered the opposite of object-oriented
84programming. Objects are little capsules containing some internal state along
85with a collection of method calls that let you modify this state, and programs
86consist of making the right set of state changes. Functional programming wants
87to avoid state changes as much as possible and works with data flowing between
88functions. In Python you might combine the two approaches by writing functions
89that take and return instances representing objects in your application (e-mail
90messages, transactions, etc.).
91
92Functional design may seem like an odd constraint to work under. Why should you
93avoid objects and side effects? There are theoretical and practical advantages
94to the functional style:
95
96* Formal provability.
97* Modularity.
98* Composability.
99* Ease of debugging and testing.
100
Christian Heimesfe337bf2008-03-23 21:54:12 +0000101
Georg Brandl116aa622007-08-15 14:28:22 +0000102Formal provability
103------------------
104
105A theoretical benefit is that it's easier to construct a mathematical proof that
106a functional program is correct.
107
108For a long time researchers have been interested in finding ways to
109mathematically prove programs correct. This is different from testing a program
110on numerous inputs and concluding that its output is usually correct, or reading
111a program's source code and concluding that the code looks right; the goal is
112instead a rigorous proof that a program produces the right result for all
113possible inputs.
114
115The technique used to prove programs correct is to write down **invariants**,
116properties of the input data and of the program's variables that are always
117true. For each line of code, you then show that if invariants X and Y are true
118**before** the line is executed, the slightly different invariants X' and Y' are
119true **after** the line is executed. This continues until you reach the end of
120the program, at which point the invariants should match the desired conditions
121on the program's output.
122
123Functional programming's avoidance of assignments arose because assignments are
124difficult to handle with this technique; assignments can break invariants that
125were true before the assignment without producing any new invariants that can be
126propagated onward.
127
128Unfortunately, proving programs correct is largely impractical and not relevant
129to Python software. Even trivial programs require proofs that are several pages
130long; the proof of correctness for a moderately complicated program would be
131enormous, and few or none of the programs you use daily (the Python interpreter,
132your XML parser, your web browser) could be proven correct. Even if you wrote
133down or generated a proof, there would then be the question of verifying the
134proof; maybe there's an error in it, and you wrongly believe you've proved the
135program correct.
136
Christian Heimesfe337bf2008-03-23 21:54:12 +0000137
Georg Brandl116aa622007-08-15 14:28:22 +0000138Modularity
139----------
140
141A more practical benefit of functional programming is that it forces you to
142break apart your problem into small pieces. Programs are more modular as a
143result. It's easier to specify and write a small function that does one thing
144than a large function that performs a complicated transformation. Small
145functions are also easier to read and to check for errors.
146
147
148Ease of debugging and testing
149-----------------------------
150
151Testing and debugging a functional-style program is easier.
152
153Debugging is simplified because functions are generally small and clearly
154specified. When a program doesn't work, each function is an interface point
155where you can check that the data are correct. You can look at the intermediate
156inputs and outputs to quickly isolate the function that's responsible for a bug.
157
158Testing is easier because each function is a potential subject for a unit test.
159Functions don't depend on system state that needs to be replicated before
160running a test; instead you only have to synthesize the right input and then
161check that the output matches expectations.
162
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164Composability
165-------------
166
167As you work on a functional-style program, you'll write a number of functions
168with varying inputs and outputs. Some of these functions will be unavoidably
169specialized to a particular application, but others will be useful in a wide
170variety of programs. For example, a function that takes a directory path and
171returns all the XML files in the directory, or a function that takes a filename
172and returns its contents, can be applied to many different situations.
173
174Over time you'll form a personal library of utilities. Often you'll assemble
175new programs by arranging existing functions in a new configuration and writing
176a few functions specialized for the current task.
177
178
Georg Brandl116aa622007-08-15 14:28:22 +0000179Iterators
180=========
181
182I'll start by looking at a Python language feature that's an important
183foundation for writing functional-style programs: iterators.
184
185An iterator is an object representing a stream of data; this object returns the
186data one element at a time. A Python iterator must support a method called
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000187``__next__()`` that takes no arguments and always returns the next element of
188the stream. If there are no more elements in the stream, ``__next__()`` must
189raise the ``StopIteration`` exception. Iterators don't have to be finite,
190though; it's perfectly reasonable to write an iterator that produces an infinite
191stream of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193The built-in :func:`iter` function takes an arbitrary object and tries to return
194an iterator that will return the object's contents or elements, raising
195:exc:`TypeError` if the object doesn't support iteration. Several of Python's
196built-in data types support iteration, the most common being lists and
197dictionaries. An object is called an **iterable** object if you can get an
198iterator for it.
199
Christian Heimesfe337bf2008-03-23 21:54:12 +0000200You can experiment with the iteration interface manually:
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202 >>> L = [1,2,3]
203 >>> it = iter(L)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000204 >>> it
Christian Heimesfe337bf2008-03-23 21:54:12 +0000205 <...iterator object at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000206 >>> it.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000207 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000208 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000209 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000210 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000211 3
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000212 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000213 Traceback (most recent call last):
214 File "<stdin>", line 1, in ?
215 StopIteration
216 >>>
217
218Python expects iterable objects in several different contexts, the most
219important being the ``for`` statement. In the statement ``for X in Y``, Y must
220be an iterator or some object for which ``iter()`` can create an iterator.
221These two statements are equivalent::
222
Georg Brandl116aa622007-08-15 14:28:22 +0000223
Christian Heimesfe337bf2008-03-23 21:54:12 +0000224 for i in iter(obj):
Neal Norwitz752abd02008-05-13 04:55:24 +0000225 print(i)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000226
227 for i in obj:
Neal Norwitz752abd02008-05-13 04:55:24 +0000228 print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230Iterators can be materialized as lists or tuples by using the :func:`list` or
Christian Heimesfe337bf2008-03-23 21:54:12 +0000231:func:`tuple` constructor functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 >>> L = [1,2,3]
234 >>> iterator = iter(L)
235 >>> t = tuple(iterator)
236 >>> t
237 (1, 2, 3)
238
239Sequence unpacking also supports iterators: if you know an iterator will return
Christian Heimesfe337bf2008-03-23 21:54:12 +0000240N elements, you can unpack them into an N-tuple:
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242 >>> L = [1,2,3]
243 >>> iterator = iter(L)
244 >>> a,b,c = iterator
245 >>> a,b,c
246 (1, 2, 3)
247
248Built-in functions such as :func:`max` and :func:`min` can take a single
249iterator argument and will return the largest or smallest element. The ``"in"``
250and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
251X is found in the stream returned by the iterator. You'll run into obvious
252problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"``
253will never return, and if the element X never appears in the stream, the
254``"in"`` operator won't return either.
255
256Note that you can only go forward in an iterator; there's no way to get the
257previous element, reset the iterator, or make a copy of it. Iterator objects
258can optionally provide these additional capabilities, but the iterator protocol
259only specifies the ``next()`` method. Functions may therefore consume all of
260the iterator's output, and if you need to do something different with the same
261stream, you'll have to create a new iterator.
262
263
264
265Data Types That Support Iterators
266---------------------------------
267
268We've already seen how lists and tuples support iterators. In fact, any Python
269sequence type, such as strings, will automatically support creation of an
270iterator.
271
272Calling :func:`iter` on a dictionary returns an iterator that will loop over the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000273dictionary's keys:
274
275.. not a doctest since dict ordering varies across Pythons
276
277::
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279 >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
280 ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
281 >>> for key in m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000282 ... print(key, m[key])
Georg Brandl116aa622007-08-15 14:28:22 +0000283 Mar 3
284 Feb 2
285 Aug 8
286 Sep 9
Christian Heimesfe337bf2008-03-23 21:54:12 +0000287 Apr 4
Georg Brandl116aa622007-08-15 14:28:22 +0000288 Jun 6
289 Jul 7
290 Jan 1
Christian Heimesfe337bf2008-03-23 21:54:12 +0000291 May 5
Georg Brandl116aa622007-08-15 14:28:22 +0000292 Nov 11
293 Dec 12
294 Oct 10
295
296Note that the order is essentially random, because it's based on the hash
297ordering of the objects in the dictionary.
298
Fred Drake2e748782007-09-04 17:33:11 +0000299Applying :func:`iter` to a dictionary always loops over the keys, but
300dictionaries have methods that return other iterators. If you want to iterate
301over values or key/value pairs, you can explicitly call the
302:meth:`values` or :meth:`items` methods to get an appropriate iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304The :func:`dict` constructor can accept an iterator that returns a finite stream
Christian Heimesfe337bf2008-03-23 21:54:12 +0000305of ``(key, value)`` tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307 >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
308 >>> dict(iter(L))
309 {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
310
311Files also support iteration by calling the ``readline()`` method until there
312are no more lines in the file. This means you can read each line of a file like
313this::
314
315 for line in file:
316 # do something for each line
317 ...
318
319Sets can take their contents from an iterable and let you iterate over the set's
320elements::
321
Georg Brandlf6945182008-02-01 11:56:49 +0000322 S = {2, 3, 5, 7, 11, 13}
Georg Brandl116aa622007-08-15 14:28:22 +0000323 for i in S:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000324 print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326
327
328Generator expressions and list comprehensions
329=============================================
330
331Two common operations on an iterator's output are 1) performing some operation
332for every element, 2) selecting a subset of elements that meet some condition.
333For example, given a list of strings, you might want to strip off trailing
334whitespace from each line or extract all the strings containing a given
335substring.
336
337List comprehensions and generator expressions (short form: "listcomps" and
338"genexps") are a concise notation for such operations, borrowed from the
339functional programming language Haskell (http://www.haskell.org). You can strip
340all the whitespace from a stream of strings with the following code::
341
Christian Heimesfe337bf2008-03-23 21:54:12 +0000342 line_list = [' line 1\n', 'line 2 \n', ...]
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Christian Heimesfe337bf2008-03-23 21:54:12 +0000344 # Generator expression -- returns iterator
345 stripped_iter = (line.strip() for line in line_list)
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Christian Heimesfe337bf2008-03-23 21:54:12 +0000347 # List comprehension -- returns list
348 stripped_list = [line.strip() for line in line_list]
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350You can select only certain elements by adding an ``"if"`` condition::
351
Christian Heimesfe337bf2008-03-23 21:54:12 +0000352 stripped_list = [line.strip() for line in line_list
353 if line != ""]
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355With a list comprehension, you get back a Python list; ``stripped_list`` is a
356list containing the resulting lines, not an iterator. Generator expressions
357return an iterator that computes the values as necessary, not needing to
358materialize all the values at once. This means that list comprehensions aren't
359useful if you're working with iterators that return an infinite stream or a very
360large amount of data. Generator expressions are preferable in these situations.
361
362Generator expressions are surrounded by parentheses ("()") and list
363comprehensions are surrounded by square brackets ("[]"). Generator expressions
364have the form::
365
366 ( expression for expr in sequence1
367 if condition1
368 for expr2 in sequence2
369 if condition2
370 for expr3 in sequence3 ...
371 if condition3
372 for exprN in sequenceN
373 if conditionN )
374
375Again, for a list comprehension only the outside brackets are different (square
376brackets instead of parentheses).
377
378The elements of the generated output will be the successive values of
379``expression``. The ``if`` clauses are all optional; if present, ``expression``
380is only evaluated and added to the result when ``condition`` is true.
381
382Generator expressions always have to be written inside parentheses, but the
383parentheses signalling a function call also count. If you want to create an
384iterator that will be immediately passed to a function you can write::
385
Christian Heimesfe337bf2008-03-23 21:54:12 +0000386 obj_total = sum(obj.count for obj in list_all_objects())
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388The ``for...in`` clauses contain the sequences to be iterated over. The
389sequences do not have to be the same length, because they are iterated over from
390left to right, **not** in parallel. For each element in ``sequence1``,
391``sequence2`` is looped over from the beginning. ``sequence3`` is then looped
392over for each resulting pair of elements from ``sequence1`` and ``sequence2``.
393
394To put it another way, a list comprehension or generator expression is
395equivalent to the following Python code::
396
397 for expr1 in sequence1:
398 if not (condition1):
399 continue # Skip this element
400 for expr2 in sequence2:
401 if not (condition2):
402 continue # Skip this element
403 ...
404 for exprN in sequenceN:
405 if not (conditionN):
406 continue # Skip this element
407
408 # Output the value of
409 # the expression.
410
411This means that when there are multiple ``for...in`` clauses but no ``if``
412clauses, the length of the resulting output will be equal to the product of the
413lengths of all the sequences. If you have two lists of length 3, the output
Christian Heimesfe337bf2008-03-23 21:54:12 +0000414list is 9 elements long:
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Christian Heimesfe337bf2008-03-23 21:54:12 +0000416.. doctest::
417 :options: +NORMALIZE_WHITESPACE
418
419 >>> seq1 = 'abc'
420 >>> seq2 = (1,2,3)
421 >>> [(x,y) for x in seq1 for y in seq2]
Georg Brandl116aa622007-08-15 14:28:22 +0000422 [('a', 1), ('a', 2), ('a', 3),
423 ('b', 1), ('b', 2), ('b', 3),
424 ('c', 1), ('c', 2), ('c', 3)]
425
426To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
427creating a tuple, it must be surrounded with parentheses. The first list
428comprehension below is a syntax error, while the second one is correct::
429
430 # Syntax error
431 [ x,y for x in seq1 for y in seq2]
432 # Correct
433 [ (x,y) for x in seq1 for y in seq2]
434
435
436Generators
437==========
438
439Generators are a special class of functions that simplify the task of writing
440iterators. Regular functions compute a value and return it, but generators
441return an iterator that returns a stream of values.
442
443You're doubtless familiar with how regular function calls work in Python or C.
444When you call a function, it gets a private namespace where its local variables
445are created. When the function reaches a ``return`` statement, the local
446variables are destroyed and the value is returned to the caller. A later call
447to the same function creates a new private namespace and a fresh set of local
448variables. But, what if the local variables weren't thrown away on exiting a
449function? What if you could later resume the function where it left off? This
450is what generators provide; they can be thought of as resumable functions.
451
Christian Heimesfe337bf2008-03-23 21:54:12 +0000452Here's the simplest example of a generator function:
453
454.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456 def generate_ints(N):
457 for i in range(N):
458 yield i
459
460Any function containing a ``yield`` keyword is a generator function; this is
Georg Brandl9afde1c2007-11-01 20:32:30 +0000461detected by Python's :term:`bytecode` compiler which compiles the function
462specially as a result.
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464When you call a generator function, it doesn't return a single value; instead it
465returns a generator object that supports the iterator protocol. On executing
466the ``yield`` expression, the generator outputs the value of ``i``, similar to a
467``return`` statement. The big difference between ``yield`` and a ``return``
468statement is that on reaching a ``yield`` the generator's state of execution is
469suspended and local variables are preserved. On the next call to the
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000470generator's ``.__next__()`` method, the function will resume executing.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Christian Heimesfe337bf2008-03-23 21:54:12 +0000472Here's a sample usage of the ``generate_ints()`` generator:
Georg Brandl116aa622007-08-15 14:28:22 +0000473
474 >>> gen = generate_ints(3)
475 >>> gen
Christian Heimesfe337bf2008-03-23 21:54:12 +0000476 <generator object at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000477 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000478 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000479 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000480 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000481 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000482 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000483 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000484 Traceback (most recent call last):
485 File "stdin", line 1, in ?
486 File "stdin", line 2, in generate_ints
487 StopIteration
488
489You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
490generate_ints(3)``.
491
492Inside a generator function, the ``return`` statement can only be used without a
493value, and signals the end of the procession of values; after executing a
494``return`` the generator cannot return any further values. ``return`` with a
495value, such as ``return 5``, is a syntax error inside a generator function. The
496end of the generator's results can also be indicated by raising
497``StopIteration`` manually, or by just letting the flow of execution fall off
498the bottom of the function.
499
500You could achieve the effect of generators manually by writing your own class
501and storing all the local variables of the generator as instance variables. For
502example, returning a list of integers could be done by setting ``self.count`` to
Benjamin Petersone7c78b22008-07-03 20:28:26 +00005030, and having the ``__next__()`` method increment ``self.count`` and return it.
Georg Brandl116aa622007-08-15 14:28:22 +0000504However, for a moderately complicated generator, writing a corresponding class
505can be much messier.
506
507The test suite included with Python's library, ``test_generators.py``, contains
508a number of more interesting examples. Here's one generator that implements an
Christian Heimesfe337bf2008-03-23 21:54:12 +0000509in-order traversal of a tree using generators recursively. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 # A recursive generator that generates Tree leaves in in-order.
512 def inorder(t):
513 if t:
514 for x in inorder(t.left):
515 yield x
516
517 yield t.label
518
519 for x in inorder(t.right):
520 yield x
521
522Two other examples in ``test_generators.py`` produce solutions for the N-Queens
523problem (placing N queens on an NxN chess board so that no queen threatens
524another) and the Knight's Tour (finding a route that takes a knight to every
525square of an NxN chessboard without visiting any square twice).
526
527
528
529Passing values into a generator
530-------------------------------
531
532In Python 2.4 and earlier, generators only produced output. Once a generator's
533code was invoked to create an iterator, there was no way to pass any new
534information into the function when its execution is resumed. You could hack
535together this ability by making the generator look at a global variable or by
536passing in some mutable object that callers then modify, but these approaches
537are messy.
538
539In Python 2.5 there's a simple way to pass values into a generator.
540:keyword:`yield` became an expression, returning a value that can be assigned to
541a variable or otherwise operated on::
542
543 val = (yield i)
544
545I recommend that you **always** put parentheses around a ``yield`` expression
546when you're doing something with the returned value, as in the above example.
547The parentheses aren't always necessary, but it's easier to always add them
548instead of having to remember when they're needed.
549
550(PEP 342 explains the exact rules, which are that a ``yield``-expression must
551always be parenthesized except when it occurs at the top-level expression on the
552right-hand side of an assignment. This means you can write ``val = yield i``
553but have to use parentheses when there's an operation, as in ``val = (yield i)
554+ 12``.)
555
556Values are sent into a generator by calling its ``send(value)`` method. This
557method resumes the generator's code and the ``yield`` expression returns the
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000558specified value. If the regular ``__next__()`` method is called, the ``yield``
Georg Brandl116aa622007-08-15 14:28:22 +0000559returns ``None``.
560
561Here's a simple counter that increments by 1 and allows changing the value of
562the internal counter.
563
Christian Heimesfe337bf2008-03-23 21:54:12 +0000564.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566 def counter (maximum):
567 i = 0
568 while i < maximum:
569 val = (yield i)
570 # If value provided, change counter
571 if val is not None:
572 i = val
573 else:
574 i += 1
575
576And here's an example of changing the counter:
577
578 >>> it = counter(10)
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000579 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000580 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000581 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000582 1
Georg Brandl6911e3c2007-09-04 07:15:32 +0000583 >>> it.send(8)
Georg Brandl116aa622007-08-15 14:28:22 +0000584 8
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000585 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000586 9
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000587 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000588 Traceback (most recent call last):
589 File ``t.py'', line 15, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 it.next()
Georg Brandl116aa622007-08-15 14:28:22 +0000591 StopIteration
592
593Because ``yield`` will often be returning ``None``, you should always check for
594this case. Don't just use its value in expressions unless you're sure that the
595``send()`` method will be the only method used resume your generator function.
596
597In addition to ``send()``, there are two other new methods on generators:
598
599* ``throw(type, value=None, traceback=None)`` is used to raise an exception
600 inside the generator; the exception is raised by the ``yield`` expression
601 where the generator's execution is paused.
602
603* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
604 terminate the iteration. On receiving this exception, the generator's code
605 must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
606 exception and doing anything else is illegal and will trigger a
607 :exc:`RuntimeError`. ``close()`` will also be called by Python's garbage
608 collector when the generator is garbage-collected.
609
610 If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
611 using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
612
613The cumulative effect of these changes is to turn generators from one-way
614producers of information into both producers and consumers.
615
616Generators also become **coroutines**, a more generalized form of subroutines.
617Subroutines are entered at one point and exited at another point (the top of the
618function, and a ``return`` statement), but coroutines can be entered, exited,
619and resumed at many different points (the ``yield`` statements).
620
621
622Built-in functions
623==================
624
625Let's look in more detail at built-in functions often used with iterators.
626
Georg Brandlf6945182008-02-01 11:56:49 +0000627Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
628features of generator expressions:
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Georg Brandlf6945182008-02-01 11:56:49 +0000630``map(f, iterA, iterB, ...)`` returns an iterator over the sequence
631 ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Christian Heimesfe337bf2008-03-23 21:54:12 +0000633 >>> def upper(s):
634 ... return s.upper()
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Christian Heimesfe337bf2008-03-23 21:54:12 +0000637 >>> map(upper, ['sentence', 'fragment'])
638 ['SENTENCE', 'FRAGMENT']
639 >>> [upper(s) for s in ['sentence', 'fragment']]
640 ['SENTENCE', 'FRAGMENT']
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Georg Brandlf6945182008-02-01 11:56:49 +0000642You can of course achieve the same effect with a list comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Georg Brandlf6945182008-02-01 11:56:49 +0000644``filter(predicate, iter)`` returns an iterator over all the sequence elements
645that meet a certain condition, and is similarly duplicated by list
Georg Brandl116aa622007-08-15 14:28:22 +0000646comprehensions. A **predicate** is a function that returns the truth value of
647some condition; for use with :func:`filter`, the predicate must take a single
648value.
649
Christian Heimesfe337bf2008-03-23 21:54:12 +0000650 >>> def is_even(x):
651 ... return (x % 2) == 0
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Christian Heimesfe337bf2008-03-23 21:54:12 +0000653 >>> filter(is_even, range(10))
654 [0, 2, 4, 6, 8]
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Georg Brandl116aa622007-08-15 14:28:22 +0000656
Christian Heimesfe337bf2008-03-23 21:54:12 +0000657This can also be written as a list comprehension:
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Georg Brandlf6945182008-02-01 11:56:49 +0000659 >>> list(x for x in range(10) if is_even(x))
Georg Brandl116aa622007-08-15 14:28:22 +0000660 [0, 2, 4, 6, 8]
661
Georg Brandl116aa622007-08-15 14:28:22 +0000662
663``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
Georg Brandlf6945182008-02-01 11:56:49 +0000664containing the count and each element. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000665
Christian Heimesfe337bf2008-03-23 21:54:12 +0000666 >>> for item in enumerate(['subject', 'verb', 'object']):
Neal Norwitz752abd02008-05-13 04:55:24 +0000667 ... print(item)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000668 (0, 'subject')
669 (1, 'verb')
670 (2, 'object')
Georg Brandl116aa622007-08-15 14:28:22 +0000671
672:func:`enumerate` is often used when looping through a list and recording the
673indexes at which certain conditions are met::
674
675 f = open('data.txt', 'r')
676 for i, line in enumerate(f):
677 if line.strip() == '':
Georg Brandl6911e3c2007-09-04 07:15:32 +0000678 print('Blank line at line #%i' % i)
Georg Brandl116aa622007-08-15 14:28:22 +0000679
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Christian Heimesfe337bf2008-03-23 21:54:12 +0000681``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the
682elements of the iterable into a list, sorts the list, and returns the sorted
683result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to
684the constructed list's ``.sort()`` method. ::
685
686 >>> import random
687 >>> # Generate 8 random numbers between [0, 10000)
688 >>> rand_list = random.sample(range(10000), 8)
689 >>> rand_list
690 [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
691 >>> sorted(rand_list)
692 [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
693 >>> sorted(rand_list, reverse=True)
694 [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
697Python wiki at http://wiki.python.org/moin/HowTo/Sorting.)
698
Georg Brandl4216d2d2008-11-22 08:27:24 +0000699
Georg Brandl116aa622007-08-15 14:28:22 +0000700The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
701iterable's contents. :func:`any` returns True if any element in the iterable is
702a true value, and :func:`all` returns True if all of the elements are true
Christian Heimesfe337bf2008-03-23 21:54:12 +0000703values:
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Christian Heimesfe337bf2008-03-23 21:54:12 +0000705 >>> any([0,1,0])
706 True
707 >>> any([0,0,0])
708 False
709 >>> any([1,1,1])
710 True
711 >>> all([0,1,0])
712 False
713 >>> all([0,0,0])
714 False
715 >>> all([1,1,1])
716 True
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718
Georg Brandl4216d2d2008-11-22 08:27:24 +0000719``zip(iterA, iterB, ...)`` takes one element from each iterable and
720returns them in a tuple::
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Georg Brandl4216d2d2008-11-22 08:27:24 +0000722 zip(['a', 'b', 'c'], (1, 2, 3)) =>
723 ('a', 1), ('b', 2), ('c', 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Georg Brandl4216d2d2008-11-22 08:27:24 +0000725It doesn't construct an in-memory list and exhaust all the input iterators
726before returning; instead tuples are constructed and returned only if they're
727requested. (The technical term for this behaviour is `lazy evaluation
728<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl4216d2d2008-11-22 08:27:24 +0000730This iterator is intended to be used with iterables that are all of the same
731length. If the iterables are of different lengths, the resulting stream will be
732the same length as the shortest iterable. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandl4216d2d2008-11-22 08:27:24 +0000734 zip(['a', 'b'], (1, 2, 3)) =>
735 ('a', 1), ('b', 2)
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Georg Brandl4216d2d2008-11-22 08:27:24 +0000737You should avoid doing this, though, because an element may be taken from the
738longer iterators and discarded. This means you can't go on to use the iterators
739further because you risk skipping a discarded element.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742The itertools module
743====================
744
745The :mod:`itertools` module contains a number of commonly-used iterators as well
746as functions for combining several iterators. This section will introduce the
747module's contents by showing small examples.
748
749The module's functions fall into a few broad classes:
750
751* Functions that create a new iterator based on an existing iterator.
752* Functions for treating an iterator's elements as function arguments.
753* Functions for selecting portions of an iterator's output.
754* A function for grouping an iterator's output.
755
756Creating new iterators
757----------------------
758
759``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
760each time. You can optionally supply the starting number, which defaults to 0::
761
Christian Heimesfe337bf2008-03-23 21:54:12 +0000762 itertools.count() =>
763 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
764 itertools.count(10) =>
765 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000766
767``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
768and returns a new iterator that returns its elements from first to last. The
Christian Heimesfe337bf2008-03-23 21:54:12 +0000769new iterator will repeat these elements infinitely. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000770
Christian Heimesfe337bf2008-03-23 21:54:12 +0000771 itertools.cycle([1,2,3,4,5]) =>
772 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
Christian Heimesfe337bf2008-03-23 21:54:12 +0000775returns the element endlessly if ``n`` is not provided. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000776
777 itertools.repeat('abc') =>
778 abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
779 itertools.repeat('abc', 5) =>
780 abc, abc, abc, abc, abc
781
782``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
783input, and returns all the elements of the first iterator, then all the elements
Christian Heimesfe337bf2008-03-23 21:54:12 +0000784of the second, and so on, until all of the iterables have been exhausted. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000785
786 itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
787 a, b, c, 1, 2, 3
788
Georg Brandl116aa622007-08-15 14:28:22 +0000789``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
790slice of the iterator. With a single ``stop`` argument, it will return the
791first ``stop`` elements. If you supply a starting index, you'll get
792``stop-start`` elements, and if you supply a value for ``step``, elements will
793be skipped accordingly. Unlike Python's string and list slicing, you can't use
Christian Heimesfe337bf2008-03-23 21:54:12 +0000794negative values for ``start``, ``stop``, or ``step``. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796 itertools.islice(range(10), 8) =>
797 0, 1, 2, 3, 4, 5, 6, 7
798 itertools.islice(range(10), 2, 8) =>
799 2, 3, 4, 5, 6, 7
800 itertools.islice(range(10), 2, 8, 2) =>
801 2, 4, 6
802
803``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
804independent iterators that will all return the contents of the source iterator.
805If you don't supply a value for ``n``, the default is 2. Replicating iterators
806requires saving some of the contents of the source iterator, so this can consume
807significant memory if the iterator is large and one of the new iterators is
Christian Heimesfe337bf2008-03-23 21:54:12 +0000808consumed more than the others. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810 itertools.tee( itertools.count() ) =>
811 iterA, iterB
812
813 where iterA ->
814 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
815
816 and iterB ->
817 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
818
819
820Calling functions on elements
821-----------------------------
822
Georg Brandl116aa622007-08-15 14:28:22 +0000823The ``operator`` module contains a set of functions corresponding to Python's
824operators. Some examples are ``operator.add(a, b)`` (adds two values),
825``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
826(returns a callable that fetches the ``"id"`` attribute).
827
828``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
829of tuples, and calls ``f()`` using these tuples as the arguments::
830
831 itertools.starmap(os.path.join,
832 [('/usr', 'bin', 'java'), ('/bin', 'python'),
833 ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
834 =>
835 /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby
836
837
838Selecting elements
839------------------
840
841Another group of functions chooses a subset of an iterator's elements based on a
842predicate.
843
Georg Brandl4216d2d2008-11-22 08:27:24 +0000844``itertools.filterfalse(predicate, iter)`` is the opposite, returning all
Georg Brandl116aa622007-08-15 14:28:22 +0000845elements for which the predicate returns false::
846
Georg Brandl4216d2d2008-11-22 08:27:24 +0000847 itertools.filterfalse(is_even, itertools.count()) =>
Georg Brandl116aa622007-08-15 14:28:22 +0000848 1, 3, 5, 7, 9, 11, 13, 15, ...
849
850``itertools.takewhile(predicate, iter)`` returns elements for as long as the
851predicate returns true. Once the predicate returns false, the iterator will
852signal the end of its results.
853
854::
855
856 def less_than_10(x):
857 return (x < 10)
858
859 itertools.takewhile(less_than_10, itertools.count()) =>
860 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
861
862 itertools.takewhile(is_even, itertools.count()) =>
863 0
864
865``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
866returns true, and then returns the rest of the iterable's results.
867
868::
869
870 itertools.dropwhile(less_than_10, itertools.count()) =>
871 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
872
873 itertools.dropwhile(is_even, itertools.count()) =>
874 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
875
876
877Grouping elements
878-----------------
879
880The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
881the most complicated. ``key_func(elem)`` is a function that can compute a key
882value for each element returned by the iterable. If you don't supply a key
883function, the key is simply each element itself.
884
885``groupby()`` collects all the consecutive elements from the underlying iterable
886that have the same key value, and returns a stream of 2-tuples containing a key
887value and an iterator for the elements with that key.
888
889::
890
891 city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
892 ('Anchorage', 'AK'), ('Nome', 'AK'),
893 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
894 ...
895 ]
896
Georg Brandl0df79792008-10-04 18:33:26 +0000897 def get_state (city_state):
898 return city_state[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900 itertools.groupby(city_list, get_state) =>
901 ('AL', iterator-1),
902 ('AK', iterator-2),
903 ('AZ', iterator-3), ...
904
905 where
906 iterator-1 =>
907 ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
908 iterator-2 =>
909 ('Anchorage', 'AK'), ('Nome', 'AK')
910 iterator-3 =>
911 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
912
913``groupby()`` assumes that the underlying iterable's contents will already be
914sorted based on the key. Note that the returned iterators also use the
915underlying iterable, so you have to consume the results of iterator-1 before
916requesting iterator-2 and its corresponding key.
917
918
919The functools module
920====================
921
922The :mod:`functools` module in Python 2.5 contains some higher-order functions.
923A **higher-order function** takes one or more functions as input and returns a
924new function. The most useful tool in this module is the
925:func:`functools.partial` function.
926
927For programs written in a functional style, you'll sometimes want to construct
928variants of existing functions that have some of the parameters filled in.
929Consider a Python function ``f(a, b, c)``; you may wish to create a new function
930``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
931one of ``f()``'s parameters. This is called "partial function application".
932
933The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
934... kwarg1=value1, kwarg2=value2)``. The resulting object is callable, so you
935can just call it to invoke ``function`` with the filled-in arguments.
936
937Here's a small but realistic example::
938
939 import functools
940
941 def log (message, subsystem):
942 "Write the contents of 'message' to the specified subsystem."
Georg Brandl6911e3c2007-09-04 07:15:32 +0000943 print('%s: %s' % (subsystem, message))
Georg Brandl116aa622007-08-15 14:28:22 +0000944 ...
945
946 server_log = functools.partial(log, subsystem='server')
947 server_log('Unable to open socket')
948
Georg Brandl4216d2d2008-11-22 08:27:24 +0000949``functools.reduce(func, iter, [initial_value])`` cumulatively performs an
950operation on all the iterable's elements and, therefore, can't be applied to
951infinite iterables. (Note it is not in :mod:`builtins`, but in the
952:mod:`functools` module.) ``func`` must be a function that takes two elements
953and returns a single value. :func:`functools.reduce` takes the first two
954elements A and B returned by the iterator and calculates ``func(A, B)``. It
955then requests the third element, C, calculates ``func(func(A, B), C)``, combines
956this result with the fourth element returned, and continues until the iterable
957is exhausted. If the iterable returns no values at all, a :exc:`TypeError`
958exception is raised. If the initial value is supplied, it's used as a starting
959point and ``func(initial_value, A)`` is the first calculation. ::
960
961 >>> import operator, functools
962 >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
963 'ABBC'
964 >>> functools.reduce(operator.concat, [])
965 Traceback (most recent call last):
966 ...
967 TypeError: reduce() of empty sequence with no initial value
968 >>> functools.reduce(operator.mul, [1,2,3], 1)
969 6
970 >>> functools.reduce(operator.mul, [], 1)
971 1
972
973If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the
974elements of the iterable. This case is so common that there's a special
975built-in called :func:`sum` to compute it:
976
977 >>> import functools
978 >>> functools.reduce(operator.add, [1,2,3,4], 0)
979 10
980 >>> sum([1,2,3,4])
981 10
982 >>> sum([])
983 0
984
985For many uses of :func:`functools.reduce`, though, it can be clearer to just write the
986obvious :keyword:`for` loop::
987
988 import functools
989 # Instead of:
990 product = functools.reduce(operator.mul, [1,2,3], 1)
991
992 # You can write:
993 product = 1
994 for i in [1,2,3]:
995 product *= i
996
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998The operator module
999-------------------
1000
1001The :mod:`operator` module was mentioned earlier. It contains a set of
1002functions corresponding to Python's operators. These functions are often useful
1003in functional-style code because they save you from writing trivial functions
1004that perform a single operation.
1005
1006Some of the functions in this module are:
1007
Georg Brandlf6945182008-02-01 11:56:49 +00001008* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ...
Georg Brandl116aa622007-08-15 14:28:22 +00001009* Logical operations: ``not_()``, ``truth()``.
1010* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1011* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1012* Object identity: ``is_()``, ``is_not()``.
1013
1014Consult the operator module's documentation for a complete list.
1015
1016
1017
1018The functional module
1019---------------------
1020
1021Collin Winter's `functional module <http://oakwinter.com/code/functional/>`__
1022provides a number of more advanced tools for functional programming. It also
1023reimplements several Python built-ins, trying to make them more intuitive to
1024those used to functional programming in other languages.
1025
1026This section contains an introduction to some of the most important functions in
1027``functional``; full documentation can be found at `the project's website
1028<http://oakwinter.com/code/functional/documentation/>`__.
1029
1030``compose(outer, inner, unpack=False)``
1031
1032The ``compose()`` function implements function composition. In other words, it
1033returns a wrapper around the ``outer`` and ``inner`` callables, such that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001034return value from ``inner`` is fed directly to ``outer``. That is, ::
Georg Brandl116aa622007-08-15 14:28:22 +00001035
Christian Heimesfe337bf2008-03-23 21:54:12 +00001036 >>> def add(a, b):
1037 ... return a + b
1038 ...
1039 >>> def double(a):
1040 ... return 2 * a
1041 ...
1042 >>> compose(double, add)(5, 6)
1043 22
Georg Brandl116aa622007-08-15 14:28:22 +00001044
Christian Heimesfe337bf2008-03-23 21:54:12 +00001045is equivalent to ::
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Christian Heimesfe337bf2008-03-23 21:54:12 +00001047 >>> double(add(5, 6))
1048 22
Georg Brandl116aa622007-08-15 14:28:22 +00001049
1050The ``unpack`` keyword is provided to work around the fact that Python functions
1051are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__. By
1052default, it is expected that the ``inner`` function will return a single object
1053and that the ``outer`` function will take a single argument. Setting the
1054``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which
Christian Heimesfe337bf2008-03-23 21:54:12 +00001055will be expanded before being passed to ``outer``. Put simply, ::
Georg Brandl116aa622007-08-15 14:28:22 +00001056
Christian Heimesfe337bf2008-03-23 21:54:12 +00001057 compose(f, g)(5, 6)
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059is equivalent to::
1060
Christian Heimesfe337bf2008-03-23 21:54:12 +00001061 f(g(5, 6))
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Christian Heimesfe337bf2008-03-23 21:54:12 +00001063while ::
Georg Brandl116aa622007-08-15 14:28:22 +00001064
Christian Heimesfe337bf2008-03-23 21:54:12 +00001065 compose(f, g, unpack=True)(5, 6)
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067is equivalent to::
1068
Christian Heimesfe337bf2008-03-23 21:54:12 +00001069 f(*g(5, 6))
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071Even though ``compose()`` only accepts two functions, it's trivial to build up a
Benjamin Peterson09310422008-09-23 13:44:44 +00001072version that will compose any number of functions. We'll use
1073:func:`functools.reduce`, ``compose()`` and ``partial()`` (the last of which is
1074provided by both ``functional`` and ``functools``). ::
Georg Brandl116aa622007-08-15 14:28:22 +00001075
Christian Heimesfe337bf2008-03-23 21:54:12 +00001076 from functional import compose, partial
Benjamin Peterson09310422008-09-23 13:44:44 +00001077 import functools
Georg Brandl116aa622007-08-15 14:28:22 +00001078
Christian Heimesfe337bf2008-03-23 21:54:12 +00001079
Benjamin Peterson09310422008-09-23 13:44:44 +00001080 multi_compose = partial(functools.reduce, compose)
Georg Brandl116aa622007-08-15 14:28:22 +00001081
1082
1083We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of
1084``"".join(...)`` that converts its arguments to string::
1085
Christian Heimesfe337bf2008-03-23 21:54:12 +00001086 from functional import compose, partial
Georg Brandl116aa622007-08-15 14:28:22 +00001087
Christian Heimesfe337bf2008-03-23 21:54:12 +00001088 join = compose("".join, partial(map, str))
Georg Brandl116aa622007-08-15 14:28:22 +00001089
1090
1091``flip(func)``
1092
1093``flip()`` wraps the callable in ``func`` and causes it to receive its
Christian Heimesfe337bf2008-03-23 21:54:12 +00001094non-keyword arguments in reverse order. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001095
Christian Heimesfe337bf2008-03-23 21:54:12 +00001096 >>> def triple(a, b, c):
1097 ... return (a, b, c)
1098 ...
1099 >>> triple(5, 6, 7)
1100 (5, 6, 7)
1101 >>>
1102 >>> flipped_triple = flip(triple)
1103 >>> flipped_triple(5, 6, 7)
1104 (7, 6, 5)
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106``foldl(func, start, iterable)``
1107
1108``foldl()`` takes a binary function, a starting value (usually some kind of
1109'zero'), and an iterable. The function is applied to the starting value and the
1110first element of the list, then the result of that and the second element of the
1111list, then the result of that and the third element of the list, and so on.
1112
1113This means that a call such as::
1114
Christian Heimesfe337bf2008-03-23 21:54:12 +00001115 foldl(f, 0, [1, 2, 3])
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117is equivalent to::
1118
Christian Heimesfe337bf2008-03-23 21:54:12 +00001119 f(f(f(0, 1), 2), 3)
Georg Brandl116aa622007-08-15 14:28:22 +00001120
1121
1122``foldl()`` is roughly equivalent to the following recursive function::
1123
Christian Heimesfe337bf2008-03-23 21:54:12 +00001124 def foldl(func, start, seq):
1125 if len(seq) == 0:
1126 return start
Georg Brandl116aa622007-08-15 14:28:22 +00001127
Christian Heimesfe337bf2008-03-23 21:54:12 +00001128 return foldl(func, func(start, seq[0]), seq[1:])
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130Speaking of equivalence, the above ``foldl`` call can be expressed in terms of
Benjamin Peterson09310422008-09-23 13:44:44 +00001131the built-in :func:`functools.reduce` like so::
Georg Brandl116aa622007-08-15 14:28:22 +00001132
Benjamin Peterson09310422008-09-23 13:44:44 +00001133 import functools
1134 functools.reduce(f, [1, 2, 3], 0)
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136
1137We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a
1138cleaner, more aesthetically-pleasing version of Python's ``"".join(...)``
1139idiom::
1140
Christian Heimesfe337bf2008-03-23 21:54:12 +00001141 from functional import foldl, partial from operator import concat
1142
1143 join = partial(foldl, concat, "")
Georg Brandl116aa622007-08-15 14:28:22 +00001144
1145
Georg Brandl4216d2d2008-11-22 08:27:24 +00001146Small functions and the lambda expression
1147=========================================
1148
1149When writing functional-style programs, you'll often need little functions that
1150act as predicates or that combine elements in some way.
1151
1152If there's a Python built-in or a module function that's suitable, you don't
1153need to define a new function at all::
1154
1155 stripped_lines = [line.strip() for line in lines]
1156 existing_files = filter(os.path.exists, file_list)
1157
1158If the function you need doesn't exist, you need to write it. One way to write
1159small functions is to use the ``lambda`` statement. ``lambda`` takes a number
1160of parameters and an expression combining these parameters, and creates a small
1161function that returns the value of the expression::
1162
1163 lowercase = lambda x: x.lower()
1164
1165 print_assign = lambda name, value: name + '=' + str(value)
1166
1167 adder = lambda x, y: x+y
1168
1169An alternative is to just use the ``def`` statement and define a function in the
1170usual way::
1171
1172 def lowercase(x):
1173 return x.lower()
1174
1175 def print_assign(name, value):
1176 return name + '=' + str(value)
1177
1178 def adder(x,y):
1179 return x + y
1180
1181Which alternative is preferable? That's a style question; my usual course is to
1182avoid using ``lambda``.
1183
1184One reason for my preference is that ``lambda`` is quite limited in the
1185functions it can define. The result has to be computable as a single
1186expression, which means you can't have multiway ``if... elif... else``
1187comparisons or ``try... except`` statements. If you try to do too much in a
1188``lambda`` statement, you'll end up with an overly complicated expression that's
1189hard to read. Quick, what's the following code doing?
1190
1191::
1192
1193 import functools
1194 total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
1195
1196You can figure it out, but it takes time to disentangle the expression to figure
1197out what's going on. Using a short nested ``def`` statements makes things a
1198little bit better::
1199
1200 import functools
1201 def combine (a, b):
1202 return 0, a[1] + b[1]
1203
1204 total = functools.reduce(combine, items)[1]
1205
1206But it would be best of all if I had simply used a ``for`` loop::
1207
1208 total = 0
1209 for a, b in items:
1210 total += b
1211
1212Or the :func:`sum` built-in and a generator expression::
1213
1214 total = sum(b for a,b in items)
1215
1216Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops.
1217
1218Fredrik Lundh once suggested the following set of rules for refactoring uses of
1219``lambda``:
1220
12211) Write a lambda function.
12222) Write a comment explaining what the heck that lambda does.
12233) Study the comment for a while, and think of a name that captures the essence
1224 of the comment.
12254) Convert the lambda to a def statement, using that name.
12265) Remove the comment.
1227
1228I really like these rules, but you're free to disagree
1229about whether this lambda-free style is better.
1230
1231
Georg Brandl116aa622007-08-15 14:28:22 +00001232Revision History and Acknowledgements
1233=====================================
1234
1235The author would like to thank the following people for offering suggestions,
1236corrections and assistance with various drafts of this article: Ian Bicking,
1237Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1238Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1239
1240Version 0.1: posted June 30 2006.
1241
1242Version 0.11: posted July 1 2006. Typo fixes.
1243
1244Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one.
1245Typo fixes.
1246
1247Version 0.21: Added more references suggested on the tutor mailing list.
1248
1249Version 0.30: Adds a section on the ``functional`` module written by Collin
1250Winter; adds short section on the operator module; a few other edits.
1251
1252
1253References
1254==========
1255
1256General
1257-------
1258
1259**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1260Gerald Jay Sussman with Julie Sussman. Full text at
1261http://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
1262chapters 2 and 3 discuss the use of sequences and streams to organize the data
1263flow inside a program. The book uses Scheme for its examples, but many of the
1264design approaches described in these chapters are applicable to functional-style
1265Python code.
1266
1267http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1268programming that uses Java examples and has a lengthy historical introduction.
1269
1270http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1271describing functional programming.
1272
1273http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1274
1275http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1276
1277Python-specific
1278---------------
1279
1280http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1281:title-reference:`Text Processing in Python` discusses functional programming
1282for text processing, in the section titled "Utilizing Higher-Order Functions in
1283Text Processing".
1284
1285Mertz also wrote a 3-part series of articles on functional programming
1286for IBM's DeveloperWorks site; see
1287`part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
1288`part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
1289`part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,
1290
1291
1292Python documentation
1293--------------------
1294
1295Documentation for the :mod:`itertools` module.
1296
1297Documentation for the :mod:`operator` module.
1298
1299:pep:`289`: "Generator Expressions"
1300
1301:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1302features in Python 2.5.
1303
1304.. comment
1305
1306 Topics to place
1307 -----------------------------
1308
1309 XXX os.walk()
1310
1311 XXX Need a large example.
1312
1313 But will an example add much? I'll post a first draft and see
1314 what the comments say.
1315
1316.. comment
1317
1318 Original outline:
1319 Introduction
1320 Idea of FP
1321 Programs built out of functions
1322 Functions are strictly input-output, no internal state
1323 Opposed to OO programming, where objects have state
1324
1325 Why FP?
1326 Formal provability
1327 Assignment is difficult to reason about
1328 Not very relevant to Python
1329 Modularity
1330 Small functions that do one thing
1331 Debuggability:
1332 Easy to test due to lack of state
1333 Easy to verify output from intermediate steps
1334 Composability
1335 You assemble a toolbox of functions that can be mixed
1336
1337 Tackling a problem
1338 Need a significant example
1339
1340 Iterators
1341 Generators
1342 The itertools module
1343 List comprehensions
1344 Small functions and the lambda statement
1345 Built-in functions
1346 map
1347 filter
Georg Brandl116aa622007-08-15 14:28:22 +00001348
1349.. comment
1350
1351 Handy little function for printing part of an iterator -- used
1352 while writing this document.
1353
1354 import itertools
1355 def print_iter(it):
1356 slice = itertools.islice(it, 10)
1357 for elem in slice[:-1]:
1358 sys.stdout.write(str(elem))
1359 sys.stdout.write(', ')
Georg Brandl6911e3c2007-09-04 07:15:32 +00001360 print(elem[-1])
Georg Brandl116aa622007-08-15 14:28:22 +00001361
1362