blob: bfd2c96397bdfa234ecbc8c909944e03a2394861 [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
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl9afde1c2007-11-01 20:32:30 +000011:term:`iterator`\s and :term:`generator`\s and relevant library modules such as
12:mod:`itertools` and :mod:`functools`.
Georg Brandl116aa622007-08-15 14:28:22 +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
Christian Heimes0449f632007-12-15 01:27:15 +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 Brandl116aa622007-08-15 14:28:22 +000057
58In a functional program, input flows through a set of functions. Each function
Christian Heimes0449f632007-12-15 01:27:15 +000059operates on its input and produces some output. Functional style discourages
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl0df79792008-10-04 18:33:26 +000069effects, for example. For example, in Python a call to the :func:`print` or
70:func:`time.sleep` function both return no useful value; they're only called for
71their side effects of sending some text to the screen or pausing execution for a
Georg Brandl116aa622007-08-15 14:28:22 +000072second.
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
Christian Heimesfe337bf2008-03-23 21:54:12 +000098
Georg Brandl116aa622007-08-15 14:28:22 +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
Christian Heimesfe337bf2008-03-23 21:54:12 +0000134
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl48310cd2009-01-03 21:18:54 +0000145Ease of debugging and testing
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl116aa622007-08-15 14:28:22 +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 Brandl116aa622007-08-15 14:28:22 +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
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000184``__next__()`` that takes no arguments and always returns the next element of
185the stream. If there are no more elements in the stream, ``__next__()`` must
186raise the ``StopIteration`` exception. Iterators don't have to be finite,
187though; it's perfectly reasonable to write an iterator that produces an infinite
188stream of data.
Georg Brandl116aa622007-08-15 14:28:22 +0000189
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
Christian Heimesfe337bf2008-03-23 21:54:12 +0000197You can experiment with the iteration interface manually:
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199 >>> L = [1,2,3]
200 >>> it = iter(L)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000201 >>> it
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202 <...iterator object at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000203 >>> it.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000204 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000205 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000206 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000207 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000208 3
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000209 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000210 Traceback (most recent call last):
211 File "<stdin>", line 1, in ?
212 StopIteration
Georg Brandl48310cd2009-01-03 21:18:54 +0000213 >>>
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl116aa622007-08-15 14:28:22 +0000220
Christian Heimesfe337bf2008-03-23 21:54:12 +0000221 for i in iter(obj):
Neal Norwitz752abd02008-05-13 04:55:24 +0000222 print(i)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000223
224 for i in obj:
Neal Norwitz752abd02008-05-13 04:55:24 +0000225 print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227Iterators can be materialized as lists or tuples by using the :func:`list` or
Christian Heimesfe337bf2008-03-23 21:54:12 +0000228:func:`tuple` constructor functions:
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 >>> L = [1,2,3]
231 >>> iterator = iter(L)
232 >>> t = tuple(iterator)
233 >>> t
234 (1, 2, 3)
235
236Sequence unpacking also supports iterators: if you know an iterator will return
Christian Heimesfe337bf2008-03-23 21:54:12 +0000237N elements, you can unpack them into an N-tuple:
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239 >>> L = [1,2,3]
240 >>> iterator = iter(L)
241 >>> a,b,c = iterator
242 >>> a,b,c
243 (1, 2, 3)
244
245Built-in functions such as :func:`max` and :func:`min` can take a single
246iterator argument and will return the largest or smallest element. The ``"in"``
247and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
248X is found in the stream returned by the iterator. You'll run into obvious
249problems if the iterator is infinite; ``max()``, ``min()``, and ``"not in"``
250will never return, and if the element X never appears in the stream, the
251``"in"`` operator won't return either.
252
253Note that you can only go forward in an iterator; there's no way to get the
254previous element, reset the iterator, or make a copy of it. Iterator objects
255can optionally provide these additional capabilities, but the iterator protocol
256only specifies the ``next()`` method. Functions may therefore consume all of
257the iterator's output, and if you need to do something different with the same
258stream, you'll have to create a new iterator.
259
260
261
262Data Types That Support Iterators
263---------------------------------
264
265We've already seen how lists and tuples support iterators. In fact, any Python
266sequence type, such as strings, will automatically support creation of an
267iterator.
268
269Calling :func:`iter` on a dictionary returns an iterator that will loop over the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000270dictionary's keys:
271
272.. not a doctest since dict ordering varies across Pythons
273
274::
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
277 ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
278 >>> for key in m:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000279 ... print(key, m[key])
Georg Brandl116aa622007-08-15 14:28:22 +0000280 Mar 3
281 Feb 2
282 Aug 8
283 Sep 9
Christian Heimesfe337bf2008-03-23 21:54:12 +0000284 Apr 4
Georg Brandl116aa622007-08-15 14:28:22 +0000285 Jun 6
286 Jul 7
287 Jan 1
Christian Heimesfe337bf2008-03-23 21:54:12 +0000288 May 5
Georg Brandl116aa622007-08-15 14:28:22 +0000289 Nov 11
290 Dec 12
291 Oct 10
292
293Note that the order is essentially random, because it's based on the hash
294ordering of the objects in the dictionary.
295
Fred Drake2e748782007-09-04 17:33:11 +0000296Applying :func:`iter` to a dictionary always loops over the keys, but
297dictionaries have methods that return other iterators. If you want to iterate
298over values or key/value pairs, you can explicitly call the
299:meth:`values` or :meth:`items` methods to get an appropriate iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301The :func:`dict` constructor can accept an iterator that returns a finite stream
Christian Heimesfe337bf2008-03-23 21:54:12 +0000302of ``(key, value)`` tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304 >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
305 >>> dict(iter(L))
306 {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
307
308Files also support iteration by calling the ``readline()`` method until there
309are no more lines in the file. This means you can read each line of a file like
310this::
311
312 for line in file:
313 # do something for each line
314 ...
315
316Sets can take their contents from an iterable and let you iterate over the set's
317elements::
318
Georg Brandlf6945182008-02-01 11:56:49 +0000319 S = {2, 3, 5, 7, 11, 13}
Georg Brandl116aa622007-08-15 14:28:22 +0000320 for i in S:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000321 print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323
324
325Generator expressions and list comprehensions
326=============================================
327
328Two common operations on an iterator's output are 1) performing some operation
329for every element, 2) selecting a subset of elements that meet some condition.
330For example, given a list of strings, you might want to strip off trailing
331whitespace from each line or extract all the strings containing a given
332substring.
333
334List comprehensions and generator expressions (short form: "listcomps" and
335"genexps") are a concise notation for such operations, borrowed from the
Ezio Melotti9e8346c2010-04-05 13:57:55 +0000336functional programming language Haskell (http://www.haskell.org/). You can strip
Georg Brandl116aa622007-08-15 14:28:22 +0000337all the whitespace from a stream of strings with the following code::
338
Christian Heimesfe337bf2008-03-23 21:54:12 +0000339 line_list = [' line 1\n', 'line 2 \n', ...]
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Christian Heimesfe337bf2008-03-23 21:54:12 +0000341 # Generator expression -- returns iterator
342 stripped_iter = (line.strip() for line in line_list)
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Christian Heimesfe337bf2008-03-23 21:54:12 +0000344 # List comprehension -- returns list
345 stripped_list = [line.strip() for line in line_list]
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347You can select only certain elements by adding an ``"if"`` condition::
348
Christian Heimesfe337bf2008-03-23 21:54:12 +0000349 stripped_list = [line.strip() for line in line_list
350 if line != ""]
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352With a list comprehension, you get back a Python list; ``stripped_list`` is a
353list containing the resulting lines, not an iterator. Generator expressions
354return an iterator that computes the values as necessary, not needing to
355materialize all the values at once. This means that list comprehensions aren't
356useful if you're working with iterators that return an infinite stream or a very
357large amount of data. Generator expressions are preferable in these situations.
358
359Generator expressions are surrounded by parentheses ("()") and list
360comprehensions are surrounded by square brackets ("[]"). Generator expressions
361have the form::
362
Georg Brandl48310cd2009-01-03 21:18:54 +0000363 ( expression for expr in sequence1
Georg Brandl116aa622007-08-15 14:28:22 +0000364 if condition1
365 for expr2 in sequence2
366 if condition2
367 for expr3 in sequence3 ...
368 if condition3
369 for exprN in sequenceN
370 if conditionN )
371
372Again, for a list comprehension only the outside brackets are different (square
373brackets instead of parentheses).
374
375The elements of the generated output will be the successive values of
376``expression``. The ``if`` clauses are all optional; if present, ``expression``
377is only evaluated and added to the result when ``condition`` is true.
378
379Generator expressions always have to be written inside parentheses, but the
380parentheses signalling a function call also count. If you want to create an
381iterator that will be immediately passed to a function you can write::
382
Christian Heimesfe337bf2008-03-23 21:54:12 +0000383 obj_total = sum(obj.count for obj in list_all_objects())
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385The ``for...in`` clauses contain the sequences to be iterated over. The
386sequences do not have to be the same length, because they are iterated over from
387left to right, **not** in parallel. For each element in ``sequence1``,
388``sequence2`` is looped over from the beginning. ``sequence3`` is then looped
389over for each resulting pair of elements from ``sequence1`` and ``sequence2``.
390
391To put it another way, a list comprehension or generator expression is
392equivalent to the following Python code::
393
394 for expr1 in sequence1:
395 if not (condition1):
396 continue # Skip this element
397 for expr2 in sequence2:
398 if not (condition2):
399 continue # Skip this element
400 ...
401 for exprN in sequenceN:
402 if not (conditionN):
403 continue # Skip this element
404
Georg Brandl48310cd2009-01-03 21:18:54 +0000405 # Output the value of
Georg Brandl116aa622007-08-15 14:28:22 +0000406 # the expression.
407
408This means that when there are multiple ``for...in`` clauses but no ``if``
409clauses, the length of the resulting output will be equal to the product of the
410lengths of all the sequences. If you have two lists of length 3, the output
Christian Heimesfe337bf2008-03-23 21:54:12 +0000411list is 9 elements long:
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Christian Heimesfe337bf2008-03-23 21:54:12 +0000413.. doctest::
414 :options: +NORMALIZE_WHITESPACE
415
416 >>> seq1 = 'abc'
417 >>> seq2 = (1,2,3)
418 >>> [(x,y) for x in seq1 for y in seq2]
Georg Brandl48310cd2009-01-03 21:18:54 +0000419 [('a', 1), ('a', 2), ('a', 3),
420 ('b', 1), ('b', 2), ('b', 3),
Georg Brandl116aa622007-08-15 14:28:22 +0000421 ('c', 1), ('c', 2), ('c', 3)]
422
423To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
424creating a tuple, it must be surrounded with parentheses. The first list
425comprehension below is a syntax error, while the second one is correct::
426
427 # Syntax error
428 [ x,y for x in seq1 for y in seq2]
429 # Correct
430 [ (x,y) for x in seq1 for y in seq2]
431
432
433Generators
434==========
435
436Generators are a special class of functions that simplify the task of writing
437iterators. Regular functions compute a value and return it, but generators
438return an iterator that returns a stream of values.
439
440You're doubtless familiar with how regular function calls work in Python or C.
441When you call a function, it gets a private namespace where its local variables
442are created. When the function reaches a ``return`` statement, the local
443variables are destroyed and the value is returned to the caller. A later call
444to the same function creates a new private namespace and a fresh set of local
445variables. But, what if the local variables weren't thrown away on exiting a
446function? What if you could later resume the function where it left off? This
447is what generators provide; they can be thought of as resumable functions.
448
Christian Heimesfe337bf2008-03-23 21:54:12 +0000449Here's the simplest example of a generator function:
450
451.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453 def generate_ints(N):
454 for i in range(N):
455 yield i
456
457Any function containing a ``yield`` keyword is a generator function; this is
Georg Brandl9afde1c2007-11-01 20:32:30 +0000458detected by Python's :term:`bytecode` compiler which compiles the function
459specially as a result.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461When you call a generator function, it doesn't return a single value; instead it
462returns a generator object that supports the iterator protocol. On executing
463the ``yield`` expression, the generator outputs the value of ``i``, similar to a
464``return`` statement. The big difference between ``yield`` and a ``return``
465statement is that on reaching a ``yield`` the generator's state of execution is
466suspended and local variables are preserved. On the next call to the
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000467generator's ``.__next__()`` method, the function will resume executing.
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Christian Heimesfe337bf2008-03-23 21:54:12 +0000469Here's a sample usage of the ``generate_ints()`` generator:
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471 >>> gen = generate_ints(3)
472 >>> gen
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000473 <generator object generate_ints at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000474 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000475 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000476 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000477 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000478 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000479 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000480 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000481 Traceback (most recent call last):
482 File "stdin", line 1, in ?
483 File "stdin", line 2, in generate_ints
484 StopIteration
485
486You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
487generate_ints(3)``.
488
489Inside a generator function, the ``return`` statement can only be used without a
490value, and signals the end of the procession of values; after executing a
491``return`` the generator cannot return any further values. ``return`` with a
492value, such as ``return 5``, is a syntax error inside a generator function. The
493end of the generator's results can also be indicated by raising
494``StopIteration`` manually, or by just letting the flow of execution fall off
495the bottom of the function.
496
497You could achieve the effect of generators manually by writing your own class
498and storing all the local variables of the generator as instance variables. For
499example, returning a list of integers could be done by setting ``self.count`` to
Benjamin Petersone7c78b22008-07-03 20:28:26 +00005000, and having the ``__next__()`` method increment ``self.count`` and return it.
Georg Brandl116aa622007-08-15 14:28:22 +0000501However, for a moderately complicated generator, writing a corresponding class
502can be much messier.
503
504The test suite included with Python's library, ``test_generators.py``, contains
505a number of more interesting examples. Here's one generator that implements an
Christian Heimesfe337bf2008-03-23 21:54:12 +0000506in-order traversal of a tree using generators recursively. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508 # A recursive generator that generates Tree leaves in in-order.
509 def inorder(t):
510 if t:
511 for x in inorder(t.left):
512 yield x
513
514 yield t.label
515
516 for x in inorder(t.right):
517 yield x
518
519Two other examples in ``test_generators.py`` produce solutions for the N-Queens
520problem (placing N queens on an NxN chess board so that no queen threatens
521another) and the Knight's Tour (finding a route that takes a knight to every
522square of an NxN chessboard without visiting any square twice).
523
524
525
526Passing values into a generator
527-------------------------------
528
529In Python 2.4 and earlier, generators only produced output. Once a generator's
530code was invoked to create an iterator, there was no way to pass any new
531information into the function when its execution is resumed. You could hack
532together this ability by making the generator look at a global variable or by
533passing in some mutable object that callers then modify, but these approaches
534are messy.
535
536In Python 2.5 there's a simple way to pass values into a generator.
537:keyword:`yield` became an expression, returning a value that can be assigned to
538a variable or otherwise operated on::
539
540 val = (yield i)
541
542I recommend that you **always** put parentheses around a ``yield`` expression
543when you're doing something with the returned value, as in the above example.
544The parentheses aren't always necessary, but it's easier to always add them
545instead of having to remember when they're needed.
546
547(PEP 342 explains the exact rules, which are that a ``yield``-expression must
548always be parenthesized except when it occurs at the top-level expression on the
549right-hand side of an assignment. This means you can write ``val = yield i``
550but have to use parentheses when there's an operation, as in ``val = (yield i)
551+ 12``.)
552
553Values are sent into a generator by calling its ``send(value)`` method. This
554method resumes the generator's code and the ``yield`` expression returns the
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000555specified value. If the regular ``__next__()`` method is called, the ``yield``
Georg Brandl116aa622007-08-15 14:28:22 +0000556returns ``None``.
557
558Here's a simple counter that increments by 1 and allows changing the value of
559the internal counter.
560
Christian Heimesfe337bf2008-03-23 21:54:12 +0000561.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563 def counter (maximum):
564 i = 0
565 while i < maximum:
566 val = (yield i)
567 # If value provided, change counter
568 if val is not None:
569 i = val
570 else:
571 i += 1
572
573And here's an example of changing the counter:
574
575 >>> it = counter(10)
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000576 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000577 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000578 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000579 1
Georg Brandl6911e3c2007-09-04 07:15:32 +0000580 >>> it.send(8)
Georg Brandl116aa622007-08-15 14:28:22 +0000581 8
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000582 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000583 9
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000584 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000585 Traceback (most recent call last):
Georg Brandl1f01deb2009-01-03 22:47:39 +0000586 File "t.py", line 15, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000587 it.next()
Georg Brandl116aa622007-08-15 14:28:22 +0000588 StopIteration
589
590Because ``yield`` will often be returning ``None``, you should always check for
591this case. Don't just use its value in expressions unless you're sure that the
592``send()`` method will be the only method used resume your generator function.
593
594In addition to ``send()``, there are two other new methods on generators:
595
596* ``throw(type, value=None, traceback=None)`` is used to raise an exception
597 inside the generator; the exception is raised by the ``yield`` expression
598 where the generator's execution is paused.
599
600* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
601 terminate the iteration. On receiving this exception, the generator's code
602 must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
603 exception and doing anything else is illegal and will trigger a
604 :exc:`RuntimeError`. ``close()`` will also be called by Python's garbage
605 collector when the generator is garbage-collected.
606
607 If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
608 using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
609
610The cumulative effect of these changes is to turn generators from one-way
611producers of information into both producers and consumers.
612
613Generators also become **coroutines**, a more generalized form of subroutines.
614Subroutines are entered at one point and exited at another point (the top of the
615function, and a ``return`` statement), but coroutines can be entered, exited,
616and resumed at many different points (the ``yield`` statements).
617
618
619Built-in functions
620==================
621
622Let's look in more detail at built-in functions often used with iterators.
623
Georg Brandlf6945182008-02-01 11:56:49 +0000624Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
625features of generator expressions:
Georg Brandl116aa622007-08-15 14:28:22 +0000626
Georg Brandl48310cd2009-01-03 21:18:54 +0000627``map(f, iterA, iterB, ...)`` returns an iterator over the sequence
Georg Brandlf6945182008-02-01 11:56:49 +0000628 ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Christian Heimesfe337bf2008-03-23 21:54:12 +0000630 >>> def upper(s):
631 ... return s.upper()
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Georg Brandl116aa622007-08-15 14:28:22 +0000633
Georg Brandla3deea12008-12-15 08:29:32 +0000634 >>> list(map(upper, ['sentence', 'fragment']))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000635 ['SENTENCE', 'FRAGMENT']
636 >>> [upper(s) for s in ['sentence', 'fragment']]
637 ['SENTENCE', 'FRAGMENT']
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Georg Brandl48310cd2009-01-03 21:18:54 +0000639You can of course achieve the same effect with a list comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Georg Brandlf6945182008-02-01 11:56:49 +0000641``filter(predicate, iter)`` returns an iterator over all the sequence elements
642that meet a certain condition, and is similarly duplicated by list
Georg Brandl116aa622007-08-15 14:28:22 +0000643comprehensions. A **predicate** is a function that returns the truth value of
644some condition; for use with :func:`filter`, the predicate must take a single
645value.
646
Christian Heimesfe337bf2008-03-23 21:54:12 +0000647 >>> def is_even(x):
648 ... return (x % 2) == 0
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Georg Brandla3deea12008-12-15 08:29:32 +0000650 >>> list(filter(is_even, range(10)))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000651 [0, 2, 4, 6, 8]
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Georg Brandl116aa622007-08-15 14:28:22 +0000653
Christian Heimesfe337bf2008-03-23 21:54:12 +0000654This can also be written as a list comprehension:
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Georg Brandlf6945182008-02-01 11:56:49 +0000656 >>> list(x for x in range(10) if is_even(x))
Georg Brandl116aa622007-08-15 14:28:22 +0000657 [0, 2, 4, 6, 8]
658
Georg Brandl116aa622007-08-15 14:28:22 +0000659
660``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
Georg Brandlf6945182008-02-01 11:56:49 +0000661containing the count and each element. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Christian Heimesfe337bf2008-03-23 21:54:12 +0000663 >>> for item in enumerate(['subject', 'verb', 'object']):
Neal Norwitz752abd02008-05-13 04:55:24 +0000664 ... print(item)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000665 (0, 'subject')
666 (1, 'verb')
667 (2, 'object')
Georg Brandl116aa622007-08-15 14:28:22 +0000668
669:func:`enumerate` is often used when looping through a list and recording the
670indexes at which certain conditions are met::
671
672 f = open('data.txt', 'r')
673 for i, line in enumerate(f):
674 if line.strip() == '':
Georg Brandl6911e3c2007-09-04 07:15:32 +0000675 print('Blank line at line #%i' % i)
Georg Brandl116aa622007-08-15 14:28:22 +0000676
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000677``sorted(iterable, [key=None], [reverse=False])`` collects all the elements of
678the iterable into a list, sorts the list, and returns the sorted result. The
679``key``, and ``reverse`` arguments are passed through to the constructed list's
680``.sort()`` method. ::
Christian Heimesfe337bf2008-03-23 21:54:12 +0000681
682 >>> import random
683 >>> # Generate 8 random numbers between [0, 10000)
684 >>> rand_list = random.sample(range(10000), 8)
685 >>> rand_list
686 [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
687 >>> sorted(rand_list)
688 [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
689 >>> sorted(rand_list, reverse=True)
690 [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
693Python wiki at http://wiki.python.org/moin/HowTo/Sorting.)
694
Georg Brandl4216d2d2008-11-22 08:27:24 +0000695
Georg Brandl116aa622007-08-15 14:28:22 +0000696The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
697iterable's contents. :func:`any` returns True if any element in the iterable is
698a true value, and :func:`all` returns True if all of the elements are true
Christian Heimesfe337bf2008-03-23 21:54:12 +0000699values:
Georg Brandl116aa622007-08-15 14:28:22 +0000700
Christian Heimesfe337bf2008-03-23 21:54:12 +0000701 >>> any([0,1,0])
702 True
703 >>> any([0,0,0])
704 False
705 >>> any([1,1,1])
706 True
707 >>> all([0,1,0])
708 False
Georg Brandl48310cd2009-01-03 21:18:54 +0000709 >>> all([0,0,0])
Christian Heimesfe337bf2008-03-23 21:54:12 +0000710 False
711 >>> all([1,1,1])
712 True
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714
Georg Brandl4216d2d2008-11-22 08:27:24 +0000715``zip(iterA, iterB, ...)`` takes one element from each iterable and
716returns them in a tuple::
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Georg Brandl4216d2d2008-11-22 08:27:24 +0000718 zip(['a', 'b', 'c'], (1, 2, 3)) =>
719 ('a', 1), ('b', 2), ('c', 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Georg Brandl4216d2d2008-11-22 08:27:24 +0000721It doesn't construct an in-memory list and exhaust all the input iterators
722before returning; instead tuples are constructed and returned only if they're
723requested. (The technical term for this behaviour is `lazy evaluation
724<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Georg Brandl4216d2d2008-11-22 08:27:24 +0000726This iterator is intended to be used with iterables that are all of the same
727length. If the iterables are of different lengths, the resulting stream will be
728the same length as the shortest iterable. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl4216d2d2008-11-22 08:27:24 +0000730 zip(['a', 'b'], (1, 2, 3)) =>
731 ('a', 1), ('b', 2)
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Georg Brandl4216d2d2008-11-22 08:27:24 +0000733You should avoid doing this, though, because an element may be taken from the
734longer iterators and discarded. This means you can't go on to use the iterators
735further because you risk skipping a discarded element.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737
738The itertools module
739====================
740
741The :mod:`itertools` module contains a number of commonly-used iterators as well
742as functions for combining several iterators. This section will introduce the
743module's contents by showing small examples.
744
745The module's functions fall into a few broad classes:
746
747* Functions that create a new iterator based on an existing iterator.
748* Functions for treating an iterator's elements as function arguments.
749* Functions for selecting portions of an iterator's output.
750* A function for grouping an iterator's output.
751
752Creating new iterators
753----------------------
754
755``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
756each time. You can optionally supply the starting number, which defaults to 0::
757
Christian Heimesfe337bf2008-03-23 21:54:12 +0000758 itertools.count() =>
759 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
760 itertools.count(10) =>
761 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000762
763``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
764and returns a new iterator that returns its elements from first to last. The
Christian Heimesfe337bf2008-03-23 21:54:12 +0000765new iterator will repeat these elements infinitely. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000766
Christian Heimesfe337bf2008-03-23 21:54:12 +0000767 itertools.cycle([1,2,3,4,5]) =>
768 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000769
770``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
Christian Heimesfe337bf2008-03-23 21:54:12 +0000771returns the element endlessly if ``n`` is not provided. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773 itertools.repeat('abc') =>
774 abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
775 itertools.repeat('abc', 5) =>
776 abc, abc, abc, abc, abc
777
778``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
779input, and returns all the elements of the first iterator, then all the elements
Christian Heimesfe337bf2008-03-23 21:54:12 +0000780of the second, and so on, until all of the iterables have been exhausted. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782 itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
783 a, b, c, 1, 2, 3
784
Georg Brandl116aa622007-08-15 14:28:22 +0000785``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
786slice of the iterator. With a single ``stop`` argument, it will return the
787first ``stop`` elements. If you supply a starting index, you'll get
788``stop-start`` elements, and if you supply a value for ``step``, elements will
789be skipped accordingly. Unlike Python's string and list slicing, you can't use
Christian Heimesfe337bf2008-03-23 21:54:12 +0000790negative values for ``start``, ``stop``, or ``step``. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000791
792 itertools.islice(range(10), 8) =>
793 0, 1, 2, 3, 4, 5, 6, 7
794 itertools.islice(range(10), 2, 8) =>
795 2, 3, 4, 5, 6, 7
796 itertools.islice(range(10), 2, 8, 2) =>
797 2, 4, 6
798
799``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
800independent iterators that will all return the contents of the source iterator.
801If you don't supply a value for ``n``, the default is 2. Replicating iterators
802requires saving some of the contents of the source iterator, so this can consume
803significant memory if the iterator is large and one of the new iterators is
Christian Heimesfe337bf2008-03-23 21:54:12 +0000804consumed more than the others. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806 itertools.tee( itertools.count() ) =>
807 iterA, iterB
808
809 where iterA ->
810 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
811
812 and iterB ->
813 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
814
815
816Calling functions on elements
817-----------------------------
818
Georg Brandl116aa622007-08-15 14:28:22 +0000819The ``operator`` module contains a set of functions corresponding to Python's
820operators. Some examples are ``operator.add(a, b)`` (adds two values),
821``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
822(returns a callable that fetches the ``"id"`` attribute).
823
824``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
825of tuples, and calls ``f()`` using these tuples as the arguments::
826
Georg Brandl48310cd2009-01-03 21:18:54 +0000827 itertools.starmap(os.path.join,
Georg Brandl116aa622007-08-15 14:28:22 +0000828 [('/usr', 'bin', 'java'), ('/bin', 'python'),
829 ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
830 =>
831 /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby
832
833
834Selecting elements
835------------------
836
837Another group of functions chooses a subset of an iterator's elements based on a
838predicate.
839
Georg Brandl4216d2d2008-11-22 08:27:24 +0000840``itertools.filterfalse(predicate, iter)`` is the opposite, returning all
Georg Brandl116aa622007-08-15 14:28:22 +0000841elements for which the predicate returns false::
842
Georg Brandl4216d2d2008-11-22 08:27:24 +0000843 itertools.filterfalse(is_even, itertools.count()) =>
Georg Brandl116aa622007-08-15 14:28:22 +0000844 1, 3, 5, 7, 9, 11, 13, 15, ...
845
846``itertools.takewhile(predicate, iter)`` returns elements for as long as the
847predicate returns true. Once the predicate returns false, the iterator will
848signal the end of its results.
849
850::
851
852 def less_than_10(x):
853 return (x < 10)
854
855 itertools.takewhile(less_than_10, itertools.count()) =>
856 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
857
858 itertools.takewhile(is_even, itertools.count()) =>
859 0
860
861``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
862returns true, and then returns the rest of the iterable's results.
863
864::
865
866 itertools.dropwhile(less_than_10, itertools.count()) =>
867 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
868
869 itertools.dropwhile(is_even, itertools.count()) =>
870 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
871
872
873Grouping elements
874-----------------
875
876The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
877the most complicated. ``key_func(elem)`` is a function that can compute a key
878value for each element returned by the iterable. If you don't supply a key
879function, the key is simply each element itself.
880
881``groupby()`` collects all the consecutive elements from the underlying iterable
882that have the same key value, and returns a stream of 2-tuples containing a key
883value and an iterator for the elements with that key.
884
885::
886
Georg Brandl48310cd2009-01-03 21:18:54 +0000887 city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
Georg Brandl116aa622007-08-15 14:28:22 +0000888 ('Anchorage', 'AK'), ('Nome', 'AK'),
Georg Brandl48310cd2009-01-03 21:18:54 +0000889 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
Georg Brandl116aa622007-08-15 14:28:22 +0000890 ...
891 ]
892
Georg Brandl0df79792008-10-04 18:33:26 +0000893 def get_state (city_state):
894 return city_state[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896 itertools.groupby(city_list, get_state) =>
897 ('AL', iterator-1),
898 ('AK', iterator-2),
899 ('AZ', iterator-3), ...
900
901 where
902 iterator-1 =>
903 ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
Georg Brandl48310cd2009-01-03 21:18:54 +0000904 iterator-2 =>
Georg Brandl116aa622007-08-15 14:28:22 +0000905 ('Anchorage', 'AK'), ('Nome', 'AK')
906 iterator-3 =>
907 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
908
909``groupby()`` assumes that the underlying iterable's contents will already be
910sorted based on the key. Note that the returned iterators also use the
911underlying iterable, so you have to consume the results of iterator-1 before
912requesting iterator-2 and its corresponding key.
913
914
915The functools module
916====================
917
918The :mod:`functools` module in Python 2.5 contains some higher-order functions.
919A **higher-order function** takes one or more functions as input and returns a
920new function. The most useful tool in this module is the
921:func:`functools.partial` function.
922
923For programs written in a functional style, you'll sometimes want to construct
924variants of existing functions that have some of the parameters filled in.
925Consider a Python function ``f(a, b, c)``; you may wish to create a new function
926``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
927one of ``f()``'s parameters. This is called "partial function application".
928
929The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
930... kwarg1=value1, kwarg2=value2)``. The resulting object is callable, so you
931can just call it to invoke ``function`` with the filled-in arguments.
932
933Here's a small but realistic example::
934
935 import functools
936
937 def log (message, subsystem):
938 "Write the contents of 'message' to the specified subsystem."
Georg Brandl6911e3c2007-09-04 07:15:32 +0000939 print('%s: %s' % (subsystem, message))
Georg Brandl116aa622007-08-15 14:28:22 +0000940 ...
941
942 server_log = functools.partial(log, subsystem='server')
943 server_log('Unable to open socket')
944
Georg Brandl4216d2d2008-11-22 08:27:24 +0000945``functools.reduce(func, iter, [initial_value])`` cumulatively performs an
946operation on all the iterable's elements and, therefore, can't be applied to
947infinite iterables. (Note it is not in :mod:`builtins`, but in the
948:mod:`functools` module.) ``func`` must be a function that takes two elements
949and returns a single value. :func:`functools.reduce` takes the first two
950elements A and B returned by the iterator and calculates ``func(A, B)``. It
951then requests the third element, C, calculates ``func(func(A, B), C)``, combines
952this result with the fourth element returned, and continues until the iterable
953is exhausted. If the iterable returns no values at all, a :exc:`TypeError`
954exception is raised. If the initial value is supplied, it's used as a starting
955point and ``func(initial_value, A)`` is the first calculation. ::
956
957 >>> import operator, functools
958 >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
959 'ABBC'
960 >>> functools.reduce(operator.concat, [])
961 Traceback (most recent call last):
962 ...
963 TypeError: reduce() of empty sequence with no initial value
964 >>> functools.reduce(operator.mul, [1,2,3], 1)
965 6
966 >>> functools.reduce(operator.mul, [], 1)
967 1
968
969If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the
970elements of the iterable. This case is so common that there's a special
971built-in called :func:`sum` to compute it:
972
973 >>> import functools
974 >>> functools.reduce(operator.add, [1,2,3,4], 0)
975 10
976 >>> sum([1,2,3,4])
977 10
978 >>> sum([])
979 0
980
981For many uses of :func:`functools.reduce`, though, it can be clearer to just write the
982obvious :keyword:`for` loop::
983
984 import functools
985 # Instead of:
986 product = functools.reduce(operator.mul, [1,2,3], 1)
987
988 # You can write:
989 product = 1
990 for i in [1,2,3]:
991 product *= i
992
Georg Brandl116aa622007-08-15 14:28:22 +0000993
994The operator module
995-------------------
996
997The :mod:`operator` module was mentioned earlier. It contains a set of
998functions corresponding to Python's operators. These functions are often useful
999in functional-style code because they save you from writing trivial functions
1000that perform a single operation.
1001
1002Some of the functions in this module are:
1003
Georg Brandlf6945182008-02-01 11:56:49 +00001004* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ...
Georg Brandl116aa622007-08-15 14:28:22 +00001005* Logical operations: ``not_()``, ``truth()``.
1006* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1007* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1008* Object identity: ``is_()``, ``is_not()``.
1009
1010Consult the operator module's documentation for a complete list.
1011
1012
1013
1014The functional module
1015---------------------
1016
1017Collin Winter's `functional module <http://oakwinter.com/code/functional/>`__
1018provides a number of more advanced tools for functional programming. It also
1019reimplements several Python built-ins, trying to make them more intuitive to
1020those used to functional programming in other languages.
1021
1022This section contains an introduction to some of the most important functions in
1023``functional``; full documentation can be found at `the project's website
1024<http://oakwinter.com/code/functional/documentation/>`__.
1025
1026``compose(outer, inner, unpack=False)``
1027
1028The ``compose()`` function implements function composition. In other words, it
1029returns a wrapper around the ``outer`` and ``inner`` callables, such that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001030return value from ``inner`` is fed directly to ``outer``. That is, ::
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Christian Heimesfe337bf2008-03-23 21:54:12 +00001032 >>> def add(a, b):
1033 ... return a + b
1034 ...
1035 >>> def double(a):
1036 ... return 2 * a
1037 ...
1038 >>> compose(double, add)(5, 6)
1039 22
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Christian Heimesfe337bf2008-03-23 21:54:12 +00001041is equivalent to ::
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Christian Heimesfe337bf2008-03-23 21:54:12 +00001043 >>> double(add(5, 6))
1044 22
Georg Brandl48310cd2009-01-03 21:18:54 +00001045
Georg Brandl116aa622007-08-15 14:28:22 +00001046The ``unpack`` keyword is provided to work around the fact that Python functions
1047are not always `fully curried <http://en.wikipedia.org/wiki/Currying>`__. By
1048default, it is expected that the ``inner`` function will return a single object
1049and that the ``outer`` function will take a single argument. Setting the
1050``unpack`` argument causes ``compose`` to expect a tuple from ``inner`` which
Christian Heimesfe337bf2008-03-23 21:54:12 +00001051will be expanded before being passed to ``outer``. Put simply, ::
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Christian Heimesfe337bf2008-03-23 21:54:12 +00001053 compose(f, g)(5, 6)
Georg Brandl48310cd2009-01-03 21:18:54 +00001054
Georg Brandl116aa622007-08-15 14:28:22 +00001055is equivalent to::
1056
Christian Heimesfe337bf2008-03-23 21:54:12 +00001057 f(g(5, 6))
Georg Brandl48310cd2009-01-03 21:18:54 +00001058
Christian Heimesfe337bf2008-03-23 21:54:12 +00001059while ::
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Christian Heimesfe337bf2008-03-23 21:54:12 +00001061 compose(f, g, unpack=True)(5, 6)
Georg Brandl48310cd2009-01-03 21:18:54 +00001062
Georg Brandl116aa622007-08-15 14:28:22 +00001063is equivalent to::
1064
Christian Heimesfe337bf2008-03-23 21:54:12 +00001065 f(*g(5, 6))
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067Even though ``compose()`` only accepts two functions, it's trivial to build up a
Benjamin Peterson09310422008-09-23 13:44:44 +00001068version that will compose any number of functions. We'll use
1069:func:`functools.reduce`, ``compose()`` and ``partial()`` (the last of which is
1070provided by both ``functional`` and ``functools``). ::
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Christian Heimesfe337bf2008-03-23 21:54:12 +00001072 from functional import compose, partial
Benjamin Peterson09310422008-09-23 13:44:44 +00001073 import functools
Georg Brandl48310cd2009-01-03 21:18:54 +00001074
Christian Heimesfe337bf2008-03-23 21:54:12 +00001075
Benjamin Peterson09310422008-09-23 13:44:44 +00001076 multi_compose = partial(functools.reduce, compose)
Georg Brandl48310cd2009-01-03 21:18:54 +00001077
1078
Georg Brandl116aa622007-08-15 14:28:22 +00001079We can also use ``map()``, ``compose()`` and ``partial()`` to craft a version of
1080``"".join(...)`` that converts its arguments to string::
1081
Christian Heimesfe337bf2008-03-23 21:54:12 +00001082 from functional import compose, partial
Georg Brandl48310cd2009-01-03 21:18:54 +00001083
Christian Heimesfe337bf2008-03-23 21:54:12 +00001084 join = compose("".join, partial(map, str))
Georg Brandl116aa622007-08-15 14:28:22 +00001085
1086
1087``flip(func)``
Georg Brandl48310cd2009-01-03 21:18:54 +00001088
Georg Brandl116aa622007-08-15 14:28:22 +00001089``flip()`` wraps the callable in ``func`` and causes it to receive its
Christian Heimesfe337bf2008-03-23 21:54:12 +00001090non-keyword arguments in reverse order. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Christian Heimesfe337bf2008-03-23 21:54:12 +00001092 >>> def triple(a, b, c):
1093 ... return (a, b, c)
1094 ...
1095 >>> triple(5, 6, 7)
1096 (5, 6, 7)
1097 >>>
1098 >>> flipped_triple = flip(triple)
1099 >>> flipped_triple(5, 6, 7)
1100 (7, 6, 5)
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102``foldl(func, start, iterable)``
Georg Brandl48310cd2009-01-03 21:18:54 +00001103
Georg Brandl116aa622007-08-15 14:28:22 +00001104``foldl()`` takes a binary function, a starting value (usually some kind of
1105'zero'), and an iterable. The function is applied to the starting value and the
1106first element of the list, then the result of that and the second element of the
1107list, then the result of that and the third element of the list, and so on.
1108
1109This means that a call such as::
1110
Christian Heimesfe337bf2008-03-23 21:54:12 +00001111 foldl(f, 0, [1, 2, 3])
Georg Brandl116aa622007-08-15 14:28:22 +00001112
1113is equivalent to::
1114
Christian Heimesfe337bf2008-03-23 21:54:12 +00001115 f(f(f(0, 1), 2), 3)
Georg Brandl116aa622007-08-15 14:28:22 +00001116
Georg Brandl48310cd2009-01-03 21:18:54 +00001117
Georg Brandl116aa622007-08-15 14:28:22 +00001118``foldl()`` is roughly equivalent to the following recursive function::
1119
Christian Heimesfe337bf2008-03-23 21:54:12 +00001120 def foldl(func, start, seq):
1121 if len(seq) == 0:
1122 return start
Georg Brandl116aa622007-08-15 14:28:22 +00001123
Christian Heimesfe337bf2008-03-23 21:54:12 +00001124 return foldl(func, func(start, seq[0]), seq[1:])
Georg Brandl116aa622007-08-15 14:28:22 +00001125
1126Speaking of equivalence, the above ``foldl`` call can be expressed in terms of
Benjamin Peterson09310422008-09-23 13:44:44 +00001127the built-in :func:`functools.reduce` like so::
Georg Brandl116aa622007-08-15 14:28:22 +00001128
Benjamin Peterson09310422008-09-23 13:44:44 +00001129 import functools
1130 functools.reduce(f, [1, 2, 3], 0)
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132
1133We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to write a
1134cleaner, more aesthetically-pleasing version of Python's ``"".join(...)``
1135idiom::
1136
Christian Heimesfe337bf2008-03-23 21:54:12 +00001137 from functional import foldl, partial from operator import concat
1138
1139 join = partial(foldl, concat, "")
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141
Georg Brandl4216d2d2008-11-22 08:27:24 +00001142Small functions and the lambda expression
1143=========================================
1144
1145When writing functional-style programs, you'll often need little functions that
1146act as predicates or that combine elements in some way.
1147
1148If there's a Python built-in or a module function that's suitable, you don't
1149need to define a new function at all::
1150
1151 stripped_lines = [line.strip() for line in lines]
1152 existing_files = filter(os.path.exists, file_list)
1153
1154If the function you need doesn't exist, you need to write it. One way to write
1155small functions is to use the ``lambda`` statement. ``lambda`` takes a number
1156of parameters and an expression combining these parameters, and creates a small
1157function that returns the value of the expression::
1158
1159 lowercase = lambda x: x.lower()
1160
1161 print_assign = lambda name, value: name + '=' + str(value)
1162
1163 adder = lambda x, y: x+y
1164
1165An alternative is to just use the ``def`` statement and define a function in the
1166usual way::
1167
1168 def lowercase(x):
1169 return x.lower()
1170
1171 def print_assign(name, value):
1172 return name + '=' + str(value)
1173
1174 def adder(x,y):
1175 return x + y
1176
1177Which alternative is preferable? That's a style question; my usual course is to
1178avoid using ``lambda``.
1179
1180One reason for my preference is that ``lambda`` is quite limited in the
1181functions it can define. The result has to be computable as a single
1182expression, which means you can't have multiway ``if... elif... else``
1183comparisons or ``try... except`` statements. If you try to do too much in a
1184``lambda`` statement, you'll end up with an overly complicated expression that's
1185hard to read. Quick, what's the following code doing?
1186
1187::
1188
1189 import functools
1190 total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
1191
1192You can figure it out, but it takes time to disentangle the expression to figure
1193out what's going on. Using a short nested ``def`` statements makes things a
1194little bit better::
1195
1196 import functools
1197 def combine (a, b):
1198 return 0, a[1] + b[1]
1199
1200 total = functools.reduce(combine, items)[1]
1201
1202But it would be best of all if I had simply used a ``for`` loop::
1203
1204 total = 0
1205 for a, b in items:
1206 total += b
1207
1208Or the :func:`sum` built-in and a generator expression::
1209
1210 total = sum(b for a,b in items)
1211
1212Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops.
1213
1214Fredrik Lundh once suggested the following set of rules for refactoring uses of
1215``lambda``:
1216
12171) Write a lambda function.
12182) Write a comment explaining what the heck that lambda does.
12193) Study the comment for a while, and think of a name that captures the essence
1220 of the comment.
12214) Convert the lambda to a def statement, using that name.
12225) Remove the comment.
1223
Georg Brandl48310cd2009-01-03 21:18:54 +00001224I really like these rules, but you're free to disagree
Georg Brandl4216d2d2008-11-22 08:27:24 +00001225about whether this lambda-free style is better.
1226
1227
Georg Brandl116aa622007-08-15 14:28:22 +00001228Revision History and Acknowledgements
1229=====================================
1230
1231The author would like to thank the following people for offering suggestions,
1232corrections and assistance with various drafts of this article: Ian Bicking,
1233Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1234Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1235
1236Version 0.1: posted June 30 2006.
1237
1238Version 0.11: posted July 1 2006. Typo fixes.
1239
1240Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one.
1241Typo fixes.
1242
1243Version 0.21: Added more references suggested on the tutor mailing list.
1244
1245Version 0.30: Adds a section on the ``functional`` module written by Collin
1246Winter; adds short section on the operator module; a few other edits.
1247
1248
1249References
1250==========
1251
1252General
1253-------
1254
1255**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1256Gerald Jay Sussman with Julie Sussman. Full text at
1257http://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
1258chapters 2 and 3 discuss the use of sequences and streams to organize the data
1259flow inside a program. The book uses Scheme for its examples, but many of the
1260design approaches described in these chapters are applicable to functional-style
1261Python code.
1262
1263http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1264programming that uses Java examples and has a lengthy historical introduction.
1265
1266http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1267describing functional programming.
1268
1269http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1270
1271http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1272
1273Python-specific
1274---------------
1275
1276http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1277:title-reference:`Text Processing in Python` discusses functional programming
1278for text processing, in the section titled "Utilizing Higher-Order Functions in
1279Text Processing".
1280
1281Mertz also wrote a 3-part series of articles on functional programming
Georg Brandl48310cd2009-01-03 21:18:54 +00001282for IBM's DeveloperWorks site; see
Georg Brandl116aa622007-08-15 14:28:22 +00001283`part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
1284`part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
1285`part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,
1286
1287
1288Python documentation
1289--------------------
1290
1291Documentation for the :mod:`itertools` module.
1292
1293Documentation for the :mod:`operator` module.
1294
1295:pep:`289`: "Generator Expressions"
1296
1297:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1298features in Python 2.5.
1299
1300.. comment
1301
1302 Topics to place
1303 -----------------------------
1304
1305 XXX os.walk()
1306
1307 XXX Need a large example.
1308
1309 But will an example add much? I'll post a first draft and see
1310 what the comments say.
1311
1312.. comment
1313
1314 Original outline:
1315 Introduction
1316 Idea of FP
1317 Programs built out of functions
1318 Functions are strictly input-output, no internal state
1319 Opposed to OO programming, where objects have state
1320
1321 Why FP?
1322 Formal provability
1323 Assignment is difficult to reason about
1324 Not very relevant to Python
1325 Modularity
1326 Small functions that do one thing
1327 Debuggability:
1328 Easy to test due to lack of state
1329 Easy to verify output from intermediate steps
1330 Composability
1331 You assemble a toolbox of functions that can be mixed
1332
1333 Tackling a problem
1334 Need a significant example
1335
1336 Iterators
1337 Generators
1338 The itertools module
1339 List comprehensions
1340 Small functions and the lambda statement
1341 Built-in functions
1342 map
1343 filter
Georg Brandl116aa622007-08-15 14:28:22 +00001344
1345.. comment
1346
1347 Handy little function for printing part of an iterator -- used
1348 while writing this document.
1349
1350 import itertools
1351 def print_iter(it):
1352 slice = itertools.islice(it, 10)
1353 for elem in slice[:-1]:
1354 sys.stdout.write(str(elem))
1355 sys.stdout.write(', ')
Georg Brandl6911e3c2007-09-04 07:15:32 +00001356 print(elem[-1])
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358