blob: 4ae216a04ac57712fedbaf53ef7bebc4b266ac3d [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001********************************
2 Functional Programming HOWTO
3********************************
4
Georg Brandl09a7fe62008-03-22 11:00:48 +00005:Author: A. M. Kuchling
Andrew M. Kuchling90921cc2007-12-14 22:52:36 +00006:Release: 0.31
Georg Brandl8ec7f652007-08-15 14:28:01 +00007
Georg Brandl8ec7f652007-08-15 14:28:01 +00008In this document, we'll take a tour of Python's features suitable for
9implementing programs in a functional style. After an introduction to the
10concepts of functional programming, we'll look at language features such as
Georg Brandle7a09902007-10-21 12:10:28 +000011:term:`iterator`\s and :term:`generator`\s and relevant library modules such as
Georg Brandlcf3fb252007-10-21 10:52:38 +000012:mod:`itertools` and :mod:`functools`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000013
14
15Introduction
16============
17
18This section explains the basic concept of functional programming; if you're
19just interested in learning about Python language features, skip to the next
20section.
21
22Programming languages support decomposing problems in several different ways:
23
24* Most programming languages are **procedural**: programs are lists of
25 instructions that tell the computer what to do with the program's input. C,
26 Pascal, and even Unix shells are procedural languages.
27
28* In **declarative** languages, you write a specification that describes the
29 problem to be solved, and the language implementation figures out how to
30 perform the computation efficiently. SQL is the declarative language you're
31 most likely to be familiar with; a SQL query describes the data set you want
32 to retrieve, and the SQL engine decides whether to scan tables or use indexes,
33 which subclauses should be performed first, etc.
34
35* **Object-oriented** programs manipulate collections of objects. Objects have
36 internal state and support methods that query or modify this internal state in
37 some way. Smalltalk and Java are object-oriented languages. C++ and Python
38 are languages that support object-oriented programming, but don't force the
39 use of object-oriented features.
40
41* **Functional** programming decomposes a problem into a set of functions.
42 Ideally, functions only take inputs and produce outputs, and don't have any
43 internal state that affects the output produced for a given input. Well-known
44 functional languages include the ML family (Standard ML, OCaml, and other
45 variants) and Haskell.
46
Andrew M. Kuchling90921cc2007-12-14 22:52:36 +000047The designers of some computer languages choose to emphasize one
48particular approach to programming. This often makes it difficult to
49write programs that use a different approach. Other languages are
50multi-paradigm languages that support several different approaches.
51Lisp, C++, and Python are multi-paradigm; you can write programs or
52libraries that are largely procedural, object-oriented, or functional
53in all of these languages. In a large program, different sections
54might be written using different approaches; the GUI might be
55object-oriented while the processing logic is procedural or
56functional, for example.
Georg Brandl8ec7f652007-08-15 14:28:01 +000057
58In a functional program, input flows through a set of functions. Each function
Andrew M. Kuchling90921cc2007-12-14 22:52:36 +000059operates on its input and produces some output. Functional style discourages
Georg Brandl8ec7f652007-08-15 14:28:01 +000060functions with side effects that modify internal state or make other changes
61that aren't visible in the function's return value. Functions that have no side
62effects at all are called **purely functional**. Avoiding side effects means
63not using data structures that get updated as a program runs; every function's
64output must only depend on its input.
65
66Some languages are very strict about purity and don't even have assignment
67statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all
68side effects. Printing to the screen or writing to a disk file are side
69effects, for example. For example, in Python a ``print`` statement or a
70``time.sleep(1)`` both return no useful value; they're only called for their
71side effects of sending some text to the screen or pausing execution for a
72second.
73
74Python programs written in functional style usually won't go to the extreme of
75avoiding all I/O or all assignments; instead, they'll provide a
76functional-appearing interface but will use non-functional features internally.
77For example, the implementation of a function will still use assignments to
78local variables, but won't modify global variables or have other side effects.
79
80Functional programming can be considered the opposite of object-oriented
81programming. Objects are little capsules containing some internal state along
82with a collection of method calls that let you modify this state, and programs
83consist of making the right set of state changes. Functional programming wants
84to avoid state changes as much as possible and works with data flowing between
85functions. In Python you might combine the two approaches by writing functions
86that take and return instances representing objects in your application (e-mail
87messages, transactions, etc.).
88
89Functional design may seem like an odd constraint to work under. Why should you
90avoid objects and side effects? There are theoretical and practical advantages
91to the functional style:
92
93* Formal provability.
94* Modularity.
95* Composability.
96* Ease of debugging and testing.
97
Georg Brandl09a7fe62008-03-22 11:00:48 +000098
Georg Brandl8ec7f652007-08-15 14:28:01 +000099Formal provability
100------------------
101
102A theoretical benefit is that it's easier to construct a mathematical proof that
103a functional program is correct.
104
105For a long time researchers have been interested in finding ways to
106mathematically prove programs correct. This is different from testing a program
107on numerous inputs and concluding that its output is usually correct, or reading
108a program's source code and concluding that the code looks right; the goal is
109instead a rigorous proof that a program produces the right result for all
110possible inputs.
111
112The technique used to prove programs correct is to write down **invariants**,
113properties of the input data and of the program's variables that are always
114true. For each line of code, you then show that if invariants X and Y are true
115**before** the line is executed, the slightly different invariants X' and Y' are
116true **after** the line is executed. This continues until you reach the end of
117the program, at which point the invariants should match the desired conditions
118on the program's output.
119
120Functional programming's avoidance of assignments arose because assignments are
121difficult to handle with this technique; assignments can break invariants that
122were true before the assignment without producing any new invariants that can be
123propagated onward.
124
125Unfortunately, proving programs correct is largely impractical and not relevant
126to Python software. Even trivial programs require proofs that are several pages
127long; the proof of correctness for a moderately complicated program would be
128enormous, and few or none of the programs you use daily (the Python interpreter,
129your XML parser, your web browser) could be proven correct. Even if you wrote
130down or generated a proof, there would then be the question of verifying the
131proof; maybe there's an error in it, and you wrongly believe you've proved the
132program correct.
133
Georg Brandl09a7fe62008-03-22 11:00:48 +0000134
Georg Brandl8ec7f652007-08-15 14:28:01 +0000135Modularity
136----------
137
138A more practical benefit of functional programming is that it forces you to
139break apart your problem into small pieces. Programs are more modular as a
140result. It's easier to specify and write a small function that does one thing
141than a large function that performs a complicated transformation. Small
142functions are also easier to read and to check for errors.
143
144
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000145Ease of debugging and testing
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146-----------------------------
147
148Testing and debugging a functional-style program is easier.
149
150Debugging is simplified because functions are generally small and clearly
151specified. When a program doesn't work, each function is an interface point
152where you can check that the data are correct. You can look at the intermediate
153inputs and outputs to quickly isolate the function that's responsible for a bug.
154
155Testing is easier because each function is a potential subject for a unit test.
156Functions don't depend on system state that needs to be replicated before
157running a test; instead you only have to synthesize the right input and then
158check that the output matches expectations.
159
160
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161Composability
162-------------
163
164As you work on a functional-style program, you'll write a number of functions
165with varying inputs and outputs. Some of these functions will be unavoidably
166specialized to a particular application, but others will be useful in a wide
167variety of programs. For example, a function that takes a directory path and
168returns all the XML files in the directory, or a function that takes a filename
169and returns its contents, can be applied to many different situations.
170
171Over time you'll form a personal library of utilities. Often you'll assemble
172new programs by arranging existing functions in a new configuration and writing
173a few functions specialized for the current task.
174
175
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176Iterators
177=========
178
179I'll start by looking at a Python language feature that's an important
180foundation for writing functional-style programs: iterators.
181
182An iterator is an object representing a stream of data; this object returns the
183data one element at a time. A Python iterator must support a method called
184``next()`` that takes no arguments and always returns the next element of the
185stream. If there are no more elements in the stream, ``next()`` must raise the
186``StopIteration`` exception. Iterators don't have to be finite, though; it's
187perfectly reasonable to write an iterator that produces an infinite stream of
188data.
189
190The built-in :func:`iter` function takes an arbitrary object and tries to return
191an iterator that will return the object's contents or elements, raising
192:exc:`TypeError` if the object doesn't support iteration. Several of Python's
193built-in data types support iteration, the most common being lists and
194dictionaries. An object is called an **iterable** object if you can get an
195iterator for it.
196
Georg Brandl09a7fe62008-03-22 11:00:48 +0000197You can experiment with the iteration interface manually:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198
199 >>> L = [1,2,3]
200 >>> it = iter(L)
201 >>> print it
Georg Brandl09a7fe62008-03-22 11:00:48 +0000202 <...iterator object at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203 >>> it.next()
204 1
205 >>> it.next()
206 2
207 >>> it.next()
208 3
209 >>> it.next()
210 Traceback (most recent call last):
211 File "<stdin>", line 1, in ?
212 StopIteration
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000213 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000214
215Python expects iterable objects in several different contexts, the most
216important being the ``for`` statement. In the statement ``for X in Y``, Y must
217be an iterator or some object for which ``iter()`` can create an iterator.
218These two statements are equivalent::
219
Georg Brandl09a7fe62008-03-22 11:00:48 +0000220 for i in iter(obj):
221 print i
Georg Brandl8ec7f652007-08-15 14:28:01 +0000222
Georg Brandl09a7fe62008-03-22 11:00:48 +0000223 for i in obj:
224 print i
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
226Iterators can be materialized as lists or tuples by using the :func:`list` or
Georg Brandl09a7fe62008-03-22 11:00:48 +0000227:func:`tuple` constructor functions:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
229 >>> L = [1,2,3]
230 >>> iterator = iter(L)
231 >>> t = tuple(iterator)
232 >>> t
233 (1, 2, 3)
234
235Sequence unpacking also supports iterators: if you know an iterator will return
Georg Brandl09a7fe62008-03-22 11:00:48 +0000236N elements, you can unpack them into an N-tuple:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
238 >>> L = [1,2,3]
239 >>> iterator = iter(L)
240 >>> a,b,c = iterator
241 >>> a,b,c
242 (1, 2, 3)
243
244Built-in functions such as :func:`max` and :func:`min` can take a single
245iterator argument and will return the largest or smallest element. The ``"in"``
246and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
247X is found in the stream returned by the iterator. You'll run into obvious
248problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"``
249will never return, and if the element X never appears in the stream, the
250``"in"`` operator won't return either.
251
252Note that you can only go forward in an iterator; there's no way to get the
253previous element, reset the iterator, or make a copy of it. Iterator objects
254can optionally provide these additional capabilities, but the iterator protocol
255only specifies the ``next()`` method. Functions may therefore consume all of
256the iterator's output, and if you need to do something different with the same
257stream, you'll have to create a new iterator.
258
259
260
261Data Types That Support Iterators
262---------------------------------
263
264We've already seen how lists and tuples support iterators. In fact, any Python
265sequence type, such as strings, will automatically support creation of an
266iterator.
267
268Calling :func:`iter` on a dictionary returns an iterator that will loop over the
Georg Brandl09a7fe62008-03-22 11:00:48 +0000269dictionary's keys:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270
Georg Brandl9f662322008-03-22 11:47:10 +0000271.. not a doctest since dict ordering varies across Pythons
272
273::
274
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275 >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
276 ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
277 >>> for key in m:
278 ... print key, m[key]
279 Mar 3
280 Feb 2
281 Aug 8
282 Sep 9
Georg Brandl09a7fe62008-03-22 11:00:48 +0000283 Apr 4
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284 Jun 6
285 Jul 7
286 Jan 1
Georg Brandl09a7fe62008-03-22 11:00:48 +0000287 May 5
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288 Nov 11
289 Dec 12
290 Oct 10
291
292Note that the order is essentially random, because it's based on the hash
293ordering of the objects in the dictionary.
294
295Applying ``iter()`` to a dictionary always loops over the keys, but dictionaries
296have methods that return other iterators. If you want to iterate over keys,
297values, or key/value pairs, you can explicitly call the ``iterkeys()``,
298``itervalues()``, or ``iteritems()`` methods to get an appropriate iterator.
299
300The :func:`dict` constructor can accept an iterator that returns a finite stream
Georg Brandl09a7fe62008-03-22 11:00:48 +0000301of ``(key, value)`` tuples:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303 >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
304 >>> dict(iter(L))
305 {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
306
307Files also support iteration by calling the ``readline()`` method until there
308are no more lines in the file. This means you can read each line of a file like
309this::
310
311 for line in file:
312 # do something for each line
313 ...
314
315Sets can take their contents from an iterable and let you iterate over the set's
316elements::
317
318 S = set((2, 3, 5, 7, 11, 13))
319 for i in S:
320 print i
321
322
323
324Generator expressions and list comprehensions
325=============================================
326
327Two common operations on an iterator's output are 1) performing some operation
328for every element, 2) selecting a subset of elements that meet some condition.
329For example, given a list of strings, you might want to strip off trailing
330whitespace from each line or extract all the strings containing a given
331substring.
332
333List comprehensions and generator expressions (short form: "listcomps" and
334"genexps") are a concise notation for such operations, borrowed from the
Ezio Melotti425aa2e2010-04-05 12:51:45 +0000335functional programming language Haskell (http://www.haskell.org/). You can strip
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336all the whitespace from a stream of strings with the following code::
337
Georg Brandl09a7fe62008-03-22 11:00:48 +0000338 line_list = [' line 1\n', 'line 2 \n', ...]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339
Georg Brandl09a7fe62008-03-22 11:00:48 +0000340 # Generator expression -- returns iterator
341 stripped_iter = (line.strip() for line in line_list)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342
Georg Brandl09a7fe62008-03-22 11:00:48 +0000343 # List comprehension -- returns list
344 stripped_list = [line.strip() for line in line_list]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345
346You can select only certain elements by adding an ``"if"`` condition::
347
Georg Brandl09a7fe62008-03-22 11:00:48 +0000348 stripped_list = [line.strip() for line in line_list
349 if line != ""]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
351With a list comprehension, you get back a Python list; ``stripped_list`` is a
352list containing the resulting lines, not an iterator. Generator expressions
353return an iterator that computes the values as necessary, not needing to
354materialize all the values at once. This means that list comprehensions aren't
355useful if you're working with iterators that return an infinite stream or a very
356large amount of data. Generator expressions are preferable in these situations.
357
358Generator expressions are surrounded by parentheses ("()") and list
359comprehensions are surrounded by square brackets ("[]"). Generator expressions
360have the form::
361
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000362 ( expression for expr in sequence1
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363 if condition1
364 for expr2 in sequence2
365 if condition2
366 for expr3 in sequence3 ...
367 if condition3
368 for exprN in sequenceN
369 if conditionN )
370
371Again, for a list comprehension only the outside brackets are different (square
372brackets instead of parentheses).
373
374The elements of the generated output will be the successive values of
375``expression``. The ``if`` clauses are all optional; if present, ``expression``
376is only evaluated and added to the result when ``condition`` is true.
377
378Generator expressions always have to be written inside parentheses, but the
379parentheses signalling a function call also count. If you want to create an
380iterator that will be immediately passed to a function you can write::
381
Georg Brandl09a7fe62008-03-22 11:00:48 +0000382 obj_total = sum(obj.count for obj in list_all_objects())
Georg Brandl8ec7f652007-08-15 14:28:01 +0000383
384The ``for...in`` clauses contain the sequences to be iterated over. The
385sequences do not have to be the same length, because they are iterated over from
386left to right, **not** in parallel. For each element in ``sequence1``,
387``sequence2`` is looped over from the beginning. ``sequence3`` is then looped
388over for each resulting pair of elements from ``sequence1`` and ``sequence2``.
389
390To put it another way, a list comprehension or generator expression is
391equivalent to the following Python code::
392
393 for expr1 in sequence1:
394 if not (condition1):
395 continue # Skip this element
396 for expr2 in sequence2:
397 if not (condition2):
398 continue # Skip this element
399 ...
400 for exprN in sequenceN:
401 if not (conditionN):
402 continue # Skip this element
403
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000404 # Output the value of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000405 # the expression.
406
407This means that when there are multiple ``for...in`` clauses but no ``if``
408clauses, the length of the resulting output will be equal to the product of the
409lengths of all the sequences. If you have two lists of length 3, the output
Georg Brandl09a7fe62008-03-22 11:00:48 +0000410list is 9 elements long:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000411
Georg Brandl09a7fe62008-03-22 11:00:48 +0000412.. doctest::
413 :options: +NORMALIZE_WHITESPACE
414
415 >>> seq1 = 'abc'
416 >>> seq2 = (1,2,3)
417 >>> [(x,y) for x in seq1 for y in seq2]
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000418 [('a', 1), ('a', 2), ('a', 3),
419 ('b', 1), ('b', 2), ('b', 3),
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420 ('c', 1), ('c', 2), ('c', 3)]
421
422To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
423creating a tuple, it must be surrounded with parentheses. The first list
424comprehension below is a syntax error, while the second one is correct::
425
426 # Syntax error
427 [ x,y for x in seq1 for y in seq2]
428 # Correct
429 [ (x,y) for x in seq1 for y in seq2]
430
431
432Generators
433==========
434
435Generators are a special class of functions that simplify the task of writing
436iterators. Regular functions compute a value and return it, but generators
437return an iterator that returns a stream of values.
438
439You're doubtless familiar with how regular function calls work in Python or C.
440When you call a function, it gets a private namespace where its local variables
441are created. When the function reaches a ``return`` statement, the local
442variables are destroyed and the value is returned to the caller. A later call
443to the same function creates a new private namespace and a fresh set of local
444variables. But, what if the local variables weren't thrown away on exiting a
445function? What if you could later resume the function where it left off? This
446is what generators provide; they can be thought of as resumable functions.
447
Georg Brandl09a7fe62008-03-22 11:00:48 +0000448Here's the simplest example of a generator function:
449
Georg Brandl838b4b02008-03-22 13:07:06 +0000450.. testcode::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000451
452 def generate_ints(N):
453 for i in range(N):
454 yield i
455
456Any function containing a ``yield`` keyword is a generator function; this is
Georg Brandl5e52db02007-10-21 10:45:46 +0000457detected by Python's :term:`bytecode` compiler which compiles the function
458specially as a result.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459
460When you call a generator function, it doesn't return a single value; instead it
461returns a generator object that supports the iterator protocol. On executing
462the ``yield`` expression, the generator outputs the value of ``i``, similar to a
463``return`` statement. The big difference between ``yield`` and a ``return``
464statement is that on reaching a ``yield`` the generator's state of execution is
465suspended and local variables are preserved. On the next call to the
466generator's ``.next()`` method, the function will resume executing.
467
Georg Brandl09a7fe62008-03-22 11:00:48 +0000468Here's a sample usage of the ``generate_ints()`` generator:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000469
470 >>> gen = generate_ints(3)
471 >>> gen
Georg Brandlf6dab952009-04-28 21:48:35 +0000472 <generator object generate_ints at ...>
Georg Brandl8ec7f652007-08-15 14:28:01 +0000473 >>> gen.next()
474 0
475 >>> gen.next()
476 1
477 >>> gen.next()
478 2
479 >>> gen.next()
480 Traceback (most recent call last):
481 File "stdin", line 1, in ?
482 File "stdin", line 2, in generate_ints
483 StopIteration
484
485You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
486generate_ints(3)``.
487
488Inside a generator function, the ``return`` statement can only be used without a
489value, and signals the end of the procession of values; after executing a
490``return`` the generator cannot return any further values. ``return`` with a
491value, such as ``return 5``, is a syntax error inside a generator function. The
492end of the generator's results can also be indicated by raising
493``StopIteration`` manually, or by just letting the flow of execution fall off
494the bottom of the function.
495
496You could achieve the effect of generators manually by writing your own class
497and storing all the local variables of the generator as instance variables. For
498example, returning a list of integers could be done by setting ``self.count`` to
4990, and having the ``next()`` method increment ``self.count`` and return it.
500However, for a moderately complicated generator, writing a corresponding class
501can be much messier.
502
503The test suite included with Python's library, ``test_generators.py``, contains
504a number of more interesting examples. Here's one generator that implements an
Georg Brandl09a7fe62008-03-22 11:00:48 +0000505in-order traversal of a tree using generators recursively. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000506
507 # A recursive generator that generates Tree leaves in in-order.
508 def inorder(t):
509 if t:
510 for x in inorder(t.left):
511 yield x
512
513 yield t.label
514
515 for x in inorder(t.right):
516 yield x
517
518Two other examples in ``test_generators.py`` produce solutions for the N-Queens
519problem (placing N queens on an NxN chess board so that no queen threatens
520another) and the Knight's Tour (finding a route that takes a knight to every
521square of an NxN chessboard without visiting any square twice).
522
523
524
525Passing values into a generator
526-------------------------------
527
528In Python 2.4 and earlier, generators only produced output. Once a generator's
529code was invoked to create an iterator, there was no way to pass any new
530information into the function when its execution is resumed. You could hack
531together this ability by making the generator look at a global variable or by
532passing in some mutable object that callers then modify, but these approaches
533are messy.
534
535In Python 2.5 there's a simple way to pass values into a generator.
536:keyword:`yield` became an expression, returning a value that can be assigned to
537a variable or otherwise operated on::
538
539 val = (yield i)
540
541I recommend that you **always** put parentheses around a ``yield`` expression
542when you're doing something with the returned value, as in the above example.
543The parentheses aren't always necessary, but it's easier to always add them
544instead of having to remember when they're needed.
545
546(PEP 342 explains the exact rules, which are that a ``yield``-expression must
547always be parenthesized except when it occurs at the top-level expression on the
548right-hand side of an assignment. This means you can write ``val = yield i``
549but have to use parentheses when there's an operation, as in ``val = (yield i)
550+ 12``.)
551
552Values are sent into a generator by calling its ``send(value)`` method. This
553method resumes the generator's code and the ``yield`` expression returns the
554specified value. If the regular ``next()`` method is called, the ``yield``
555returns ``None``.
556
557Here's a simple counter that increments by 1 and allows changing the value of
558the internal counter.
559
Georg Brandl838b4b02008-03-22 13:07:06 +0000560.. testcode::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
562 def counter (maximum):
563 i = 0
564 while i < maximum:
565 val = (yield i)
566 # If value provided, change counter
567 if val is not None:
568 i = val
569 else:
570 i += 1
571
572And here's an example of changing the counter:
573
574 >>> it = counter(10)
575 >>> print it.next()
576 0
577 >>> print it.next()
578 1
579 >>> print it.send(8)
580 8
581 >>> print it.next()
582 9
583 >>> print it.next()
584 Traceback (most recent call last):
Georg Brandlfc29f272009-01-02 20:25:14 +0000585 File "t.py", line 15, in ?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000586 print it.next()
587 StopIteration
588
589Because ``yield`` will often be returning ``None``, you should always check for
590this case. Don't just use its value in expressions unless you're sure that the
591``send()`` method will be the only method used resume your generator function.
592
593In addition to ``send()``, there are two other new methods on generators:
594
595* ``throw(type, value=None, traceback=None)`` is used to raise an exception
596 inside the generator; the exception is raised by the ``yield`` expression
597 where the generator's execution is paused.
598
599* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
600 terminate the iteration. On receiving this exception, the generator's code
601 must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
602 exception and doing anything else is illegal and will trigger a
603 :exc:`RuntimeError`. ``close()`` will also be called by Python's garbage
604 collector when the generator is garbage-collected.
605
606 If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
607 using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
608
609The cumulative effect of these changes is to turn generators from one-way
610producers of information into both producers and consumers.
611
612Generators also become **coroutines**, a more generalized form of subroutines.
613Subroutines are entered at one point and exited at another point (the top of the
614function, and a ``return`` statement), but coroutines can be entered, exited,
615and resumed at many different points (the ``yield`` statements).
616
617
618Built-in functions
619==================
620
621Let's look in more detail at built-in functions often used with iterators.
622
Andrew M. Kuchling90921cc2007-12-14 22:52:36 +0000623Two of Python's built-in functions, :func:`map` and :func:`filter`, are somewhat
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624obsolete; they duplicate the features of list comprehensions but return actual
625lists instead of iterators.
626
627``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], iterB[0]),
628f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
629
Georg Brandl09a7fe62008-03-22 11:00:48 +0000630 >>> def upper(s):
631 ... return s.upper()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632
Georg Brandl09a7fe62008-03-22 11:00:48 +0000633 >>> map(upper, ['sentence', 'fragment'])
634 ['SENTENCE', 'FRAGMENT']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Georg Brandl09a7fe62008-03-22 11:00:48 +0000636 >>> [upper(s) for s in ['sentence', 'fragment']]
637 ['SENTENCE', 'FRAGMENT']
Georg Brandl8ec7f652007-08-15 14:28:01 +0000638
639As shown above, you can achieve the same effect with a list comprehension. The
640:func:`itertools.imap` function does the same thing but can handle infinite
641iterators; it'll be discussed later, in the section on the :mod:`itertools` module.
642
643``filter(predicate, iter)`` returns a list that contains all the sequence
644elements that meet a certain condition, and is similarly duplicated by list
645comprehensions. A **predicate** is a function that returns the truth value of
646some condition; for use with :func:`filter`, the predicate must take a single
647value.
648
Georg Brandl09a7fe62008-03-22 11:00:48 +0000649 >>> def is_even(x):
650 ... return (x % 2) == 0
Georg Brandl8ec7f652007-08-15 14:28:01 +0000651
Georg Brandl09a7fe62008-03-22 11:00:48 +0000652 >>> filter(is_even, range(10))
653 [0, 2, 4, 6, 8]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Georg Brandl09a7fe62008-03-22 11:00:48 +0000655This can also be written as a list comprehension:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656
657 >>> [x for x in range(10) if is_even(x)]
658 [0, 2, 4, 6, 8]
659
660:func:`filter` also has a counterpart in the :mod:`itertools` module,
661:func:`itertools.ifilter`, that returns an iterator and can therefore handle
662infinite sequences just as :func:`itertools.imap` can.
663
664``reduce(func, iter, [initial_value])`` doesn't have a counterpart in the
665:mod:`itertools` module because it cumulatively performs an operation on all the
666iterable's elements and therefore can't be applied to infinite iterables.
667``func`` must be a function that takes two elements and returns a single value.
668:func:`reduce` takes the first two elements A and B returned by the iterator and
669calculates ``func(A, B)``. It then requests the third element, C, calculates
670``func(func(A, B), C)``, combines this result with the fourth element returned,
671and continues until the iterable is exhausted. If the iterable returns no
672values at all, a :exc:`TypeError` exception is raised. If the initial value is
673supplied, it's used as a starting point and ``func(initial_value, A)`` is the
674first calculation.
675
Georg Brandl09a7fe62008-03-22 11:00:48 +0000676 >>> import operator
677 >>> reduce(operator.concat, ['A', 'BB', 'C'])
678 'ABBC'
679 >>> reduce(operator.concat, [])
680 Traceback (most recent call last):
681 ...
682 TypeError: reduce() of empty sequence with no initial value
683 >>> reduce(operator.mul, [1,2,3], 1)
684 6
685 >>> reduce(operator.mul, [], 1)
686 1
Georg Brandl8ec7f652007-08-15 14:28:01 +0000687
688If you use :func:`operator.add` with :func:`reduce`, you'll add up all the
689elements of the iterable. This case is so common that there's a special
Georg Brandl09a7fe62008-03-22 11:00:48 +0000690built-in called :func:`sum` to compute it:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000691
Georg Brandl09a7fe62008-03-22 11:00:48 +0000692 >>> reduce(operator.add, [1,2,3,4], 0)
693 10
694 >>> sum([1,2,3,4])
695 10
696 >>> sum([])
697 0
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698
699For many uses of :func:`reduce`, though, it can be clearer to just write the
700obvious :keyword:`for` loop::
701
702 # Instead of:
703 product = reduce(operator.mul, [1,2,3], 1)
704
705 # You can write:
706 product = 1
707 for i in [1,2,3]:
708 product *= i
709
710
711``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
712containing the count and each element.
713
Georg Brandl09a7fe62008-03-22 11:00:48 +0000714 >>> for item in enumerate(['subject', 'verb', 'object']):
715 ... print item
716 (0, 'subject')
717 (1, 'verb')
718 (2, 'object')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719
720:func:`enumerate` is often used when looping through a list and recording the
721indexes at which certain conditions are met::
722
723 f = open('data.txt', 'r')
724 for i, line in enumerate(f):
725 if line.strip() == '':
726 print 'Blank line at line #%i' % i
727
Benjamin Peterson3e1c67e2008-12-14 17:26:04 +0000728``sorted(iterable, [cmp=None], [key=None], [reverse=False])`` collects all the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729elements of the iterable into a list, sorts the list, and returns the sorted
730result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to
Georg Brandl09a7fe62008-03-22 11:00:48 +0000731the constructed list's ``.sort()`` method. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000732
Georg Brandl09a7fe62008-03-22 11:00:48 +0000733 >>> import random
734 >>> # Generate 8 random numbers between [0, 10000)
735 >>> rand_list = random.sample(range(10000), 8)
736 >>> rand_list
737 [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
738 >>> sorted(rand_list)
739 [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
740 >>> sorted(rand_list, reverse=True)
741 [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000742
743(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
744Python wiki at http://wiki.python.org/moin/HowTo/Sorting.)
745
746The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
747iterable's contents. :func:`any` returns True if any element in the iterable is
748a true value, and :func:`all` returns True if all of the elements are true
Georg Brandl09a7fe62008-03-22 11:00:48 +0000749values:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
Georg Brandl09a7fe62008-03-22 11:00:48 +0000751 >>> any([0,1,0])
752 True
753 >>> any([0,0,0])
754 False
755 >>> any([1,1,1])
756 True
757 >>> all([0,1,0])
758 False
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000759 >>> all([0,0,0])
Georg Brandl09a7fe62008-03-22 11:00:48 +0000760 False
761 >>> all([1,1,1])
762 True
Georg Brandl8ec7f652007-08-15 14:28:01 +0000763
764
765Small functions and the lambda expression
766=========================================
767
768When writing functional-style programs, you'll often need little functions that
769act as predicates or that combine elements in some way.
770
771If there's a Python built-in or a module function that's suitable, you don't
772need to define a new function at all::
773
Georg Brandl09a7fe62008-03-22 11:00:48 +0000774 stripped_lines = [line.strip() for line in lines]
775 existing_files = filter(os.path.exists, file_list)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776
777If the function you need doesn't exist, you need to write it. One way to write
778small functions is to use the ``lambda`` statement. ``lambda`` takes a number
779of parameters and an expression combining these parameters, and creates a small
780function that returns the value of the expression::
781
Georg Brandl09a7fe62008-03-22 11:00:48 +0000782 lowercase = lambda x: x.lower()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000783
Georg Brandl09a7fe62008-03-22 11:00:48 +0000784 print_assign = lambda name, value: name + '=' + str(value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
Georg Brandl09a7fe62008-03-22 11:00:48 +0000786 adder = lambda x, y: x+y
Georg Brandl8ec7f652007-08-15 14:28:01 +0000787
788An alternative is to just use the ``def`` statement and define a function in the
789usual way::
790
Georg Brandl09a7fe62008-03-22 11:00:48 +0000791 def lowercase(x):
792 return x.lower()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000793
Georg Brandl09a7fe62008-03-22 11:00:48 +0000794 def print_assign(name, value):
795 return name + '=' + str(value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000796
Georg Brandl09a7fe62008-03-22 11:00:48 +0000797 def adder(x,y):
798 return x + y
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
800Which alternative is preferable? That's a style question; my usual course is to
801avoid using ``lambda``.
802
803One reason for my preference is that ``lambda`` is quite limited in the
804functions it can define. The result has to be computable as a single
805expression, which means you can't have multiway ``if... elif... else``
806comparisons or ``try... except`` statements. If you try to do too much in a
807``lambda`` statement, you'll end up with an overly complicated expression that's
808hard to read. Quick, what's the following code doing?
809
810::
811
812 total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
813
814You can figure it out, but it takes time to disentangle the expression to figure
815out what's going on. Using a short nested ``def`` statements makes things a
816little bit better::
817
818 def combine (a, b):
819 return 0, a[1] + b[1]
820
821 total = reduce(combine, items)[1]
822
823But it would be best of all if I had simply used a ``for`` loop::
824
825 total = 0
826 for a, b in items:
827 total += b
828
829Or the :func:`sum` built-in and a generator expression::
830
831 total = sum(b for a,b in items)
832
833Many uses of :func:`reduce` are clearer when written as ``for`` loops.
834
835Fredrik Lundh once suggested the following set of rules for refactoring uses of
836``lambda``:
837
8381) Write a lambda function.
8392) Write a comment explaining what the heck that lambda does.
8403) Study the comment for a while, and think of a name that captures the essence
841 of the comment.
8424) Convert the lambda to a def statement, using that name.
8435) Remove the comment.
844
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000845I really like these rules, but you're free to disagree
Andrew M. Kuchling90921cc2007-12-14 22:52:36 +0000846about whether this lambda-free style is better.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847
848
849The itertools module
850====================
851
852The :mod:`itertools` module contains a number of commonly-used iterators as well
853as functions for combining several iterators. This section will introduce the
854module's contents by showing small examples.
855
856The module's functions fall into a few broad classes:
857
858* Functions that create a new iterator based on an existing iterator.
859* Functions for treating an iterator's elements as function arguments.
860* Functions for selecting portions of an iterator's output.
861* A function for grouping an iterator's output.
862
863Creating new iterators
864----------------------
865
866``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
867each time. You can optionally supply the starting number, which defaults to 0::
868
Georg Brandl09a7fe62008-03-22 11:00:48 +0000869 itertools.count() =>
870 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
871 itertools.count(10) =>
872 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000873
874``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
875and returns a new iterator that returns its elements from first to last. The
Georg Brandl09a7fe62008-03-22 11:00:48 +0000876new iterator will repeat these elements infinitely. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000877
Georg Brandl09a7fe62008-03-22 11:00:48 +0000878 itertools.cycle([1,2,3,4,5]) =>
879 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000880
881``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
Georg Brandl09a7fe62008-03-22 11:00:48 +0000882returns the element endlessly if ``n`` is not provided. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883
884 itertools.repeat('abc') =>
885 abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
886 itertools.repeat('abc', 5) =>
887 abc, abc, abc, abc, abc
888
889``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
890input, and returns all the elements of the first iterator, then all the elements
Georg Brandl09a7fe62008-03-22 11:00:48 +0000891of the second, and so on, until all of the iterables have been exhausted. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892
893 itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
894 a, b, c, 1, 2, 3
895
896``itertools.izip(iterA, iterB, ...)`` takes one element from each iterable and
897returns them in a tuple::
898
899 itertools.izip(['a', 'b', 'c'], (1, 2, 3)) =>
900 ('a', 1), ('b', 2), ('c', 3)
901
Georg Brandl907a7202008-02-22 12:31:45 +0000902It's similar to the built-in :func:`zip` function, but doesn't construct an
Georg Brandl8ec7f652007-08-15 14:28:01 +0000903in-memory list and exhaust all the input iterators before returning; instead
904tuples are constructed and returned only if they're requested. (The technical
905term for this behaviour is `lazy evaluation
906<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
907
908This iterator is intended to be used with iterables that are all of the same
909length. If the iterables are of different lengths, the resulting stream will be
Georg Brandl09a7fe62008-03-22 11:00:48 +0000910the same length as the shortest iterable. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000911
912 itertools.izip(['a', 'b'], (1, 2, 3)) =>
913 ('a', 1), ('b', 2)
914
915You should avoid doing this, though, because an element may be taken from the
916longer iterators and discarded. This means you can't go on to use the iterators
917further because you risk skipping a discarded element.
918
919``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
920slice of the iterator. With a single ``stop`` argument, it will return the
921first ``stop`` elements. If you supply a starting index, you'll get
922``stop-start`` elements, and if you supply a value for ``step``, elements will
923be skipped accordingly. Unlike Python's string and list slicing, you can't use
Georg Brandl09a7fe62008-03-22 11:00:48 +0000924negative values for ``start``, ``stop``, or ``step``. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000925
926 itertools.islice(range(10), 8) =>
927 0, 1, 2, 3, 4, 5, 6, 7
928 itertools.islice(range(10), 2, 8) =>
929 2, 3, 4, 5, 6, 7
930 itertools.islice(range(10), 2, 8, 2) =>
931 2, 4, 6
932
933``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
934independent iterators that will all return the contents of the source iterator.
935If you don't supply a value for ``n``, the default is 2. Replicating iterators
936requires saving some of the contents of the source iterator, so this can consume
937significant memory if the iterator is large and one of the new iterators is
Georg Brandl09a7fe62008-03-22 11:00:48 +0000938consumed more than the others. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000939
940 itertools.tee( itertools.count() ) =>
941 iterA, iterB
942
943 where iterA ->
944 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
945
946 and iterB ->
947 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
948
949
950Calling functions on elements
951-----------------------------
952
953Two functions are used for calling other functions on the contents of an
954iterable.
955
956``itertools.imap(f, iterA, iterB, ...)`` returns a stream containing
957``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``::
958
959 itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) =>
960 6, 8, 8
961
962The ``operator`` module contains a set of functions corresponding to Python's
963operators. Some examples are ``operator.add(a, b)`` (adds two values),
964``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
965(returns a callable that fetches the ``"id"`` attribute).
966
967``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
968of tuples, and calls ``f()`` using these tuples as the arguments::
969
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000970 itertools.starmap(os.path.join,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000971 [('/usr', 'bin', 'java'), ('/bin', 'python'),
972 ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
973 =>
974 /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby
975
976
977Selecting elements
978------------------
979
980Another group of functions chooses a subset of an iterator's elements based on a
981predicate.
982
983``itertools.ifilter(predicate, iter)`` returns all the elements for which the
984predicate returns true::
985
986 def is_even(x):
987 return (x % 2) == 0
988
989 itertools.ifilter(is_even, itertools.count()) =>
990 0, 2, 4, 6, 8, 10, 12, 14, ...
991
992``itertools.ifilterfalse(predicate, iter)`` is the opposite, returning all
993elements for which the predicate returns false::
994
995 itertools.ifilterfalse(is_even, itertools.count()) =>
996 1, 3, 5, 7, 9, 11, 13, 15, ...
997
998``itertools.takewhile(predicate, iter)`` returns elements for as long as the
999predicate returns true. Once the predicate returns false, the iterator will
1000signal the end of its results.
1001
1002::
1003
1004 def less_than_10(x):
1005 return (x < 10)
1006
1007 itertools.takewhile(less_than_10, itertools.count()) =>
1008 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
1009
1010 itertools.takewhile(is_even, itertools.count()) =>
1011 0
1012
1013``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
1014returns true, and then returns the rest of the iterable's results.
1015
1016::
1017
1018 itertools.dropwhile(less_than_10, itertools.count()) =>
1019 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
1020
1021 itertools.dropwhile(is_even, itertools.count()) =>
1022 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
1023
1024
1025Grouping elements
1026-----------------
1027
1028The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
1029the most complicated. ``key_func(elem)`` is a function that can compute a key
1030value for each element returned by the iterable. If you don't supply a key
1031function, the key is simply each element itself.
1032
1033``groupby()`` collects all the consecutive elements from the underlying iterable
1034that have the same key value, and returns a stream of 2-tuples containing a key
1035value and an iterator for the elements with that key.
1036
1037::
1038
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001039 city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040 ('Anchorage', 'AK'), ('Nome', 'AK'),
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001041 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001042 ...
1043 ]
1044
1045 def get_state ((city, state)):
1046 return state
1047
1048 itertools.groupby(city_list, get_state) =>
1049 ('AL', iterator-1),
1050 ('AK', iterator-2),
1051 ('AZ', iterator-3), ...
1052
1053 where
1054 iterator-1 =>
1055 ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001056 iterator-2 =>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001057 ('Anchorage', 'AK'), ('Nome', 'AK')
1058 iterator-3 =>
1059 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
1060
1061``groupby()`` assumes that the underlying iterable's contents will already be
1062sorted based on the key. Note that the returned iterators also use the
1063underlying iterable, so you have to consume the results of iterator-1 before
1064requesting iterator-2 and its corresponding key.
1065
1066
1067The functools module
1068====================
1069
1070The :mod:`functools` module in Python 2.5 contains some higher-order functions.
1071A **higher-order function** takes one or more functions as input and returns a
1072new function. The most useful tool in this module is the
1073:func:`functools.partial` function.
1074
1075For programs written in a functional style, you'll sometimes want to construct
1076variants of existing functions that have some of the parameters filled in.
1077Consider a Python function ``f(a, b, c)``; you may wish to create a new function
1078``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
1079one of ``f()``'s parameters. This is called "partial function application".
1080
1081The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
1082... kwarg1=value1, kwarg2=value2)``. The resulting object is callable, so you
1083can just call it to invoke ``function`` with the filled-in arguments.
1084
1085Here's a small but realistic example::
1086
1087 import functools
1088
1089 def log (message, subsystem):
1090 "Write the contents of 'message' to the specified subsystem."
1091 print '%s: %s' % (subsystem, message)
1092 ...
1093
1094 server_log = functools.partial(log, subsystem='server')
1095 server_log('Unable to open socket')
1096
1097
1098The operator module
1099-------------------
1100
1101The :mod:`operator` module was mentioned earlier. It contains a set of
1102functions corresponding to Python's operators. These functions are often useful
1103in functional-style code because they save you from writing trivial functions
1104that perform a single operation.
1105
1106Some of the functions in this module are:
1107
1108* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``,
1109 ``abs()``, ...
1110* Logical operations: ``not_()``, ``truth()``.
1111* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1112* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1113* Object identity: ``is_()``, ``is_not()``.
1114
1115Consult the operator module's documentation for a complete list.
1116
1117
1118
1119The functional module
1120---------------------
1121
1122Collin Winter's `functional module <http://oakwinter.com/code/functional/>`__
1123provides a number of more advanced tools for functional programming. It also
1124reimplements several Python built-ins, trying to make them more intuitive to
1125those used to functional programming in other languages.
1126
1127This section contains an introduction to some of the most important functions in
1128``functional``; full documentation can be found at `the project's website
1129<http://oakwinter.com/code/functional/documentation/>`__.
1130
1131``compose(outer, inner, unpack=False)``
1132
1133The ``compose()`` function implements function composition. In other words, it
1134returns a wrapper around the ``outer`` and ``inner`` callables, such that the
Georg Brandl09a7fe62008-03-22 11:00:48 +00001135return value from ``inner`` is fed directly to ``outer``. That is, ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001136
Georg Brandl09a7fe62008-03-22 11:00:48 +00001137 >>> def add(a, b):
1138 ... return a + b
1139 ...
1140 >>> def double(a):
1141 ... return 2 * a
1142 ...
1143 >>> compose(double, add)(5, 6)
1144 22
Georg Brandl8ec7f652007-08-15 14:28:01 +00001145
Georg Brandl09a7fe62008-03-22 11:00:48 +00001146is equivalent to ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001147
Georg Brandl09a7fe62008-03-22 11:00:48 +00001148 >>> double(add(5, 6))
1149 22
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001150
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151The ``unpack`` keyword is provided to work around the fact that Python functions
1152are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__. By
1153default, it is expected that the ``inner`` function will return a single object
1154and that the ``outer`` function will take a single argument. Setting the
1155``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which
Georg Brandl09a7fe62008-03-22 11:00:48 +00001156will be expanded before being passed to ``outer``. Put simply, ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001157
Georg Brandl09a7fe62008-03-22 11:00:48 +00001158 compose(f, g)(5, 6)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001159
Georg Brandl8ec7f652007-08-15 14:28:01 +00001160is equivalent to::
1161
Georg Brandl09a7fe62008-03-22 11:00:48 +00001162 f(g(5, 6))
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001163
Georg Brandl09a7fe62008-03-22 11:00:48 +00001164while ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001165
Georg Brandl09a7fe62008-03-22 11:00:48 +00001166 compose(f, g, unpack=True)(5, 6)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001167
Georg Brandl8ec7f652007-08-15 14:28:01 +00001168is equivalent to::
1169
Georg Brandl09a7fe62008-03-22 11:00:48 +00001170 f(*g(5, 6))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001171
1172Even though ``compose()`` only accepts two functions, it's trivial to build up a
1173version that will compose any number of functions. We'll use ``reduce()``,
1174``compose()`` and ``partial()`` (the last of which is provided by both
Georg Brandl09a7fe62008-03-22 11:00:48 +00001175``functional`` and ``functools``). ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176
Georg Brandl09a7fe62008-03-22 11:00:48 +00001177 from functional import compose, partial
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001178
Georg Brandl09a7fe62008-03-22 11:00:48 +00001179 multi_compose = partial(reduce, compose)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001180
1181
Georg Brandl8ec7f652007-08-15 14:28:01 +00001182We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of
1183``"".join(...)`` that converts its arguments to string::
1184
Georg Brandl09a7fe62008-03-22 11:00:48 +00001185 from functional import compose, partial
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001186
Georg Brandl09a7fe62008-03-22 11:00:48 +00001187 join = compose("".join, partial(map, str))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001188
1189
1190``flip(func)``
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001191
Georg Brandl8ec7f652007-08-15 14:28:01 +00001192``flip()`` wraps the callable in ``func`` and causes it to receive its
Georg Brandl09a7fe62008-03-22 11:00:48 +00001193non-keyword arguments in reverse order. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001194
Georg Brandl09a7fe62008-03-22 11:00:48 +00001195 >>> def triple(a, b, c):
1196 ... return (a, b, c)
1197 ...
1198 >>> triple(5, 6, 7)
1199 (5, 6, 7)
1200 >>>
1201 >>> flipped_triple = flip(triple)
1202 >>> flipped_triple(5, 6, 7)
1203 (7, 6, 5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001204
1205``foldl(func, start, iterable)``
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001206
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207``foldl()`` takes a binary function, a starting value (usually some kind of
1208'zero'), and an iterable. The function is applied to the starting value and the
1209first element of the list, then the result of that and the second element of the
1210list, then the result of that and the third element of the list, and so on.
1211
1212This means that a call such as::
1213
Georg Brandl09a7fe62008-03-22 11:00:48 +00001214 foldl(f, 0, [1, 2, 3])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001215
1216is equivalent to::
1217
Georg Brandl09a7fe62008-03-22 11:00:48 +00001218 f(f(f(0, 1), 2), 3)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001219
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001220
Georg Brandl8ec7f652007-08-15 14:28:01 +00001221``foldl()`` is roughly equivalent to the following recursive function::
1222
Georg Brandl09a7fe62008-03-22 11:00:48 +00001223 def foldl(func, start, seq):
1224 if len(seq) == 0:
1225 return start
Georg Brandl8ec7f652007-08-15 14:28:01 +00001226
Georg Brandl09a7fe62008-03-22 11:00:48 +00001227 return foldl(func, func(start, seq[0]), seq[1:])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001228
1229Speaking of equivalence, the above ``foldl`` call can be expressed in terms of
1230the built-in ``reduce`` like so::
1231
Georg Brandl09a7fe62008-03-22 11:00:48 +00001232 reduce(f, [1, 2, 3], 0)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001233
1234
1235We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a
1236cleaner, more aesthetically-pleasing version of Python's ``"".join(...)``
1237idiom::
1238
Georg Brandl09a7fe62008-03-22 11:00:48 +00001239 from functional import foldl, partial from operator import concat
1240
1241 join = partial(foldl, concat, "")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001242
1243
1244Revision History and Acknowledgements
1245=====================================
1246
1247The author would like to thank the following people for offering suggestions,
1248corrections and assistance with various drafts of this article: Ian Bicking,
1249Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1250Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1251
1252Version 0.1: posted June 30 2006.
1253
1254Version 0.11: posted July 1 2006. Typo fixes.
1255
1256Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one.
1257Typo fixes.
1258
1259Version 0.21: Added more references suggested on the tutor mailing list.
1260
1261Version 0.30: Adds a section on the ``functional`` module written by Collin
1262Winter; adds short section on the operator module; a few other edits.
1263
1264
1265References
1266==========
1267
1268General
1269-------
1270
1271**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1272Gerald Jay Sussman with Julie Sussman. Full text at
1273http://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
1274chapters 2 and 3 discuss the use of sequences and streams to organize the data
1275flow inside a program. The book uses Scheme for its examples, but many of the
1276design approaches described in these chapters are applicable to functional-style
1277Python code.
1278
1279http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1280programming that uses Java examples and has a lengthy historical introduction.
1281
1282http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1283describing functional programming.
1284
1285http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1286
1287http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1288
1289Python-specific
1290---------------
1291
1292http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1293:title-reference:`Text Processing in Python` discusses functional programming
1294for text processing, in the section titled "Utilizing Higher-Order Functions in
1295Text Processing".
1296
1297Mertz also wrote a 3-part series of articles on functional programming
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001298for IBM's DeveloperWorks site; see
Georg Brandl8ec7f652007-08-15 14:28:01 +00001299`part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
1300`part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
1301`part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,
1302
1303
1304Python documentation
1305--------------------
1306
1307Documentation for the :mod:`itertools` module.
1308
1309Documentation for the :mod:`operator` module.
1310
1311:pep:`289`: "Generator Expressions"
1312
1313:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1314features in Python 2.5.
1315
1316.. comment
1317
1318 Topics to place
1319 -----------------------------
1320
1321 XXX os.walk()
1322
1323 XXX Need a large example.
1324
1325 But will an example add much? I'll post a first draft and see
1326 what the comments say.
1327
1328.. comment
1329
1330 Original outline:
1331 Introduction
1332 Idea of FP
1333 Programs built out of functions
1334 Functions are strictly input-output, no internal state
1335 Opposed to OO programming, where objects have state
1336
1337 Why FP?
1338 Formal provability
1339 Assignment is difficult to reason about
1340 Not very relevant to Python
1341 Modularity
1342 Small functions that do one thing
1343 Debuggability:
1344 Easy to test due to lack of state
1345 Easy to verify output from intermediate steps
1346 Composability
1347 You assemble a toolbox of functions that can be mixed
1348
1349 Tackling a problem
1350 Need a significant example
1351
1352 Iterators
1353 Generators
1354 The itertools module
1355 List comprehensions
1356 Small functions and the lambda statement
1357 Built-in functions
1358 map
1359 filter
1360 reduce
1361
1362.. comment
1363
1364 Handy little function for printing part of an iterator -- used
1365 while writing this document.
1366
1367 import itertools
1368 def print_iter(it):
1369 slice = itertools.islice(it, 10)
1370 for elem in slice[:-1]:
1371 sys.stdout.write(str(elem))
1372 sys.stdout.write(', ')
1373 print elem[-1]
1374
1375