blob: ebbb229e570f009517bf1ccf0f0784affdb71ece [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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300184:meth:`~iterator.__next__` that takes no arguments and always returns the next
185element of the stream. If there are no more elements in the stream,
186:meth:`~iterator.__next__` must raise the :exc:`StopIteration` exception.
187Iterators don't have to be finite, though; it's perfectly reasonable to write
188an iterator that produces an infinite stream 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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300194dictionaries. An object is called :term:`iterable` if you can get an iterator
195for it.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
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)
Ezio Melotti35cbf162012-10-12 13:24:19 +0300201 >>> it #doctest: +ELLIPSIS
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202 <...iterator object at ...>
Ezio Melotti45a101d2012-10-12 12:42:51 +0300203 >>> it.__next__() # same as next(it)
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300216important being the :keyword:`for` statement. In the statement ``for X in Y``,
217Y must be an iterator or some object for which :func:`iter` can create an
218iterator. These two statements are equivalent::
Georg Brandl116aa622007-08-15 14:28:22 +0000219
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300249problems if the iterator is infinite; :func:`max`, :func:`min`
Georg Brandl116aa622007-08-15 14:28:22 +0000250will never return, and if the element X never appears in the stream, the
Sandro Tosidd7c5522012-08-15 21:37:35 +0200251``"in"`` and ``"not in"`` operators won't return either.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300256only specifies the :meth:`~iterator.__next__` method. Functions may therefore
257consume all of the iterator's output, and if you need to do something different
258with the same stream, you'll have to create a new iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000259
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
Ezio Melotti35cbf162012-10-12 13:24:19 +0300270dictionary's keys::
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272 >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
273 ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
Ezio Melotti35cbf162012-10-12 13:24:19 +0300274 >>> for key in m: #doctest: +SKIP
Georg Brandl6911e3c2007-09-04 07:15:32 +0000275 ... print(key, m[key])
Georg Brandl116aa622007-08-15 14:28:22 +0000276 Mar 3
277 Feb 2
278 Aug 8
279 Sep 9
Christian Heimesfe337bf2008-03-23 21:54:12 +0000280 Apr 4
Georg Brandl116aa622007-08-15 14:28:22 +0000281 Jun 6
282 Jul 7
283 Jan 1
Christian Heimesfe337bf2008-03-23 21:54:12 +0000284 May 5
Georg Brandl116aa622007-08-15 14:28:22 +0000285 Nov 11
286 Dec 12
287 Oct 10
288
289Note that the order is essentially random, because it's based on the hash
290ordering of the objects in the dictionary.
291
Fred Drake2e748782007-09-04 17:33:11 +0000292Applying :func:`iter` to a dictionary always loops over the keys, but
293dictionaries have methods that return other iterators. If you want to iterate
294over values or key/value pairs, you can explicitly call the
Ezio Melotti45a101d2012-10-12 12:42:51 +0300295:meth:`~dict.values` or :meth:`~dict.items` methods to get an appropriate iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297The :func:`dict` constructor can accept an iterator that returns a finite stream
Christian Heimesfe337bf2008-03-23 21:54:12 +0000298of ``(key, value)`` tuples:
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300 >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
301 >>> dict(iter(L))
302 {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}
303
Ezio Melotti45a101d2012-10-12 12:42:51 +0300304Files also support iteration by calling the :meth:`~io.TextIOBase.readline`
305method until there are no more lines in the file. This means you can read each
306line of a file like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308 for line in file:
309 # do something for each line
310 ...
311
312Sets can take their contents from an iterable and let you iterate over the set's
313elements::
314
Georg Brandlf6945182008-02-01 11:56:49 +0000315 S = {2, 3, 5, 7, 11, 13}
Georg Brandl116aa622007-08-15 14:28:22 +0000316 for i in S:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000317 print(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319
320
321Generator expressions and list comprehensions
322=============================================
323
324Two common operations on an iterator's output are 1) performing some operation
325for every element, 2) selecting a subset of elements that meet some condition.
326For example, given a list of strings, you might want to strip off trailing
327whitespace from each line or extract all the strings containing a given
328substring.
329
330List comprehensions and generator expressions (short form: "listcomps" and
331"genexps") are a concise notation for such operations, borrowed from the
Ezio Melotti19192dd2010-04-05 13:25:51 +0000332functional programming language Haskell (http://www.haskell.org/). You can strip
Georg Brandl116aa622007-08-15 14:28:22 +0000333all the whitespace from a stream of strings with the following code::
334
Christian Heimesfe337bf2008-03-23 21:54:12 +0000335 line_list = [' line 1\n', 'line 2 \n', ...]
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Christian Heimesfe337bf2008-03-23 21:54:12 +0000337 # Generator expression -- returns iterator
338 stripped_iter = (line.strip() for line in line_list)
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Christian Heimesfe337bf2008-03-23 21:54:12 +0000340 # List comprehension -- returns list
341 stripped_list = [line.strip() for line in line_list]
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343You can select only certain elements by adding an ``"if"`` condition::
344
Christian Heimesfe337bf2008-03-23 21:54:12 +0000345 stripped_list = [line.strip() for line in line_list
346 if line != ""]
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348With a list comprehension, you get back a Python list; ``stripped_list`` is a
349list containing the resulting lines, not an iterator. Generator expressions
350return an iterator that computes the values as necessary, not needing to
351materialize all the values at once. This means that list comprehensions aren't
352useful if you're working with iterators that return an infinite stream or a very
353large amount of data. Generator expressions are preferable in these situations.
354
355Generator expressions are surrounded by parentheses ("()") and list
356comprehensions are surrounded by square brackets ("[]"). Generator expressions
357have the form::
358
Georg Brandl48310cd2009-01-03 21:18:54 +0000359 ( expression for expr in sequence1
Georg Brandl116aa622007-08-15 14:28:22 +0000360 if condition1
361 for expr2 in sequence2
362 if condition2
363 for expr3 in sequence3 ...
364 if condition3
365 for exprN in sequenceN
366 if conditionN )
367
368Again, for a list comprehension only the outside brackets are different (square
369brackets instead of parentheses).
370
371The elements of the generated output will be the successive values of
372``expression``. The ``if`` clauses are all optional; if present, ``expression``
373is only evaluated and added to the result when ``condition`` is true.
374
375Generator expressions always have to be written inside parentheses, but the
376parentheses signalling a function call also count. If you want to create an
377iterator that will be immediately passed to a function you can write::
378
Christian Heimesfe337bf2008-03-23 21:54:12 +0000379 obj_total = sum(obj.count for obj in list_all_objects())
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381The ``for...in`` clauses contain the sequences to be iterated over. The
382sequences do not have to be the same length, because they are iterated over from
383left to right, **not** in parallel. For each element in ``sequence1``,
384``sequence2`` is looped over from the beginning. ``sequence3`` is then looped
385over for each resulting pair of elements from ``sequence1`` and ``sequence2``.
386
387To put it another way, a list comprehension or generator expression is
388equivalent to the following Python code::
389
390 for expr1 in sequence1:
391 if not (condition1):
392 continue # Skip this element
393 for expr2 in sequence2:
394 if not (condition2):
395 continue # Skip this element
396 ...
397 for exprN in sequenceN:
398 if not (conditionN):
399 continue # Skip this element
400
Georg Brandl48310cd2009-01-03 21:18:54 +0000401 # Output the value of
Georg Brandl116aa622007-08-15 14:28:22 +0000402 # the expression.
403
404This means that when there are multiple ``for...in`` clauses but no ``if``
405clauses, the length of the resulting output will be equal to the product of the
406lengths of all the sequences. If you have two lists of length 3, the output
Christian Heimesfe337bf2008-03-23 21:54:12 +0000407list is 9 elements long:
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Christian Heimesfe337bf2008-03-23 21:54:12 +0000409 >>> seq1 = 'abc'
410 >>> seq2 = (1,2,3)
Ezio Melotti35cbf162012-10-12 13:24:19 +0300411 >>> [(x, y) for x in seq1 for y in seq2] #doctest: +NORMALIZE_WHITESPACE
Georg Brandl48310cd2009-01-03 21:18:54 +0000412 [('a', 1), ('a', 2), ('a', 3),
413 ('b', 1), ('b', 2), ('b', 3),
Georg Brandl116aa622007-08-15 14:28:22 +0000414 ('c', 1), ('c', 2), ('c', 3)]
415
416To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
417creating a tuple, it must be surrounded with parentheses. The first list
418comprehension below is a syntax error, while the second one is correct::
419
420 # Syntax error
Ezio Melotti45a101d2012-10-12 12:42:51 +0300421 [x, y for x in seq1 for y in seq2]
Georg Brandl116aa622007-08-15 14:28:22 +0000422 # Correct
Ezio Melotti45a101d2012-10-12 12:42:51 +0300423 [(x, y) for x in seq1 for y in seq2]
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
426Generators
427==========
428
429Generators are a special class of functions that simplify the task of writing
430iterators. Regular functions compute a value and return it, but generators
431return an iterator that returns a stream of values.
432
433You're doubtless familiar with how regular function calls work in Python or C.
434When you call a function, it gets a private namespace where its local variables
435are created. When the function reaches a ``return`` statement, the local
436variables are destroyed and the value is returned to the caller. A later call
437to the same function creates a new private namespace and a fresh set of local
438variables. But, what if the local variables weren't thrown away on exiting a
439function? What if you could later resume the function where it left off? This
440is what generators provide; they can be thought of as resumable functions.
441
Christian Heimesfe337bf2008-03-23 21:54:12 +0000442Here's the simplest example of a generator function:
443
Ezio Melotti35cbf162012-10-12 13:24:19 +0300444 >>> def generate_ints(N):
445 ... for i in range(N):
446 ... yield i
Georg Brandl116aa622007-08-15 14:28:22 +0000447
Ezio Melotti45a101d2012-10-12 12:42:51 +0300448Any function containing a :keyword:`yield` keyword is a generator function;
449this is detected by Python's :term:`bytecode` compiler which compiles the
450function specially as a result.
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452When you call a generator function, it doesn't return a single value; instead it
453returns a generator object that supports the iterator protocol. On executing
454the ``yield`` expression, the generator outputs the value of ``i``, similar to a
455``return`` statement. The big difference between ``yield`` and a ``return``
456statement is that on reaching a ``yield`` the generator's state of execution is
457suspended and local variables are preserved. On the next call to the
Ezio Melotti45a101d2012-10-12 12:42:51 +0300458generator's :meth:`~generator.__next__` method, the function will resume
459executing.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
Christian Heimesfe337bf2008-03-23 21:54:12 +0000461Here's a sample usage of the ``generate_ints()`` generator:
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463 >>> gen = generate_ints(3)
Ezio Melotti35cbf162012-10-12 13:24:19 +0300464 >>> gen #doctest: +ELLIPSIS
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000465 <generator object generate_ints at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000466 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000467 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000468 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000469 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000470 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000471 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000472 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000473 Traceback (most recent call last):
474 File "stdin", line 1, in ?
475 File "stdin", line 2, in generate_ints
476 StopIteration
477
478You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
479generate_ints(3)``.
480
481Inside a generator function, the ``return`` statement can only be used without a
482value, and signals the end of the procession of values; after executing a
483``return`` the generator cannot return any further values. ``return`` with a
484value, such as ``return 5``, is a syntax error inside a generator function. The
485end of the generator's results can also be indicated by raising
Ezio Melotti45a101d2012-10-12 12:42:51 +0300486:exc:`StopIteration` manually, or by just letting the flow of execution fall off
Georg Brandl116aa622007-08-15 14:28:22 +0000487the bottom of the function.
488
489You could achieve the effect of generators manually by writing your own class
490and storing all the local variables of the generator as instance variables. For
491example, returning a list of integers could be done by setting ``self.count`` to
Ezio Melotti45a101d2012-10-12 12:42:51 +03004920, and having the :meth:`~iterator.__next__` method increment ``self.count`` and
493return it.
Georg Brandl116aa622007-08-15 14:28:22 +0000494However, for a moderately complicated generator, writing a corresponding class
495can be much messier.
496
Ezio Melotti45a101d2012-10-12 12:42:51 +0300497The test suite included with Python's library,
498:source:`Lib/test/test_generators.py`, contains
Georg Brandl116aa622007-08-15 14:28:22 +0000499a number of more interesting examples. Here's one generator that implements an
Christian Heimesfe337bf2008-03-23 21:54:12 +0000500in-order traversal of a tree using generators recursively. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000501
502 # A recursive generator that generates Tree leaves in in-order.
503 def inorder(t):
504 if t:
505 for x in inorder(t.left):
506 yield x
507
508 yield t.label
509
510 for x in inorder(t.right):
511 yield x
512
513Two other examples in ``test_generators.py`` produce solutions for the N-Queens
514problem (placing N queens on an NxN chess board so that no queen threatens
515another) and the Knight's Tour (finding a route that takes a knight to every
516square of an NxN chessboard without visiting any square twice).
517
518
519
520Passing values into a generator
521-------------------------------
522
523In Python 2.4 and earlier, generators only produced output. Once a generator's
524code was invoked to create an iterator, there was no way to pass any new
525information into the function when its execution is resumed. You could hack
526together this ability by making the generator look at a global variable or by
527passing in some mutable object that callers then modify, but these approaches
528are messy.
529
530In Python 2.5 there's a simple way to pass values into a generator.
531:keyword:`yield` became an expression, returning a value that can be assigned to
532a variable or otherwise operated on::
533
534 val = (yield i)
535
536I recommend that you **always** put parentheses around a ``yield`` expression
537when you're doing something with the returned value, as in the above example.
538The parentheses aren't always necessary, but it's easier to always add them
539instead of having to remember when they're needed.
540
Ezio Melotti45a101d2012-10-12 12:42:51 +0300541(:pep:`342` explains the exact rules, which are that a ``yield``-expression must
Georg Brandl116aa622007-08-15 14:28:22 +0000542always be parenthesized except when it occurs at the top-level expression on the
543right-hand side of an assignment. This means you can write ``val = yield i``
544but have to use parentheses when there's an operation, as in ``val = (yield i)
545+ 12``.)
546
Ezio Melotti45a101d2012-10-12 12:42:51 +0300547Values are sent into a generator by calling its :meth:`send(value)
548<generator.send>` method. This method resumes the generator's code and the
549``yield`` expression returns the specified value. If the regular
550:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000551
552Here's a simple counter that increments by 1 and allows changing the value of
553the internal counter.
554
Christian Heimesfe337bf2008-03-23 21:54:12 +0000555.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Ezio Melotti45a101d2012-10-12 12:42:51 +0300557 def counter(maximum):
Georg Brandl116aa622007-08-15 14:28:22 +0000558 i = 0
559 while i < maximum:
560 val = (yield i)
561 # If value provided, change counter
562 if val is not None:
563 i = val
564 else:
565 i += 1
566
567And here's an example of changing the counter:
568
Ezio Melotti35cbf162012-10-12 13:24:19 +0300569 >>> it = counter(10) #doctest: +SKIP
570 >>> next(it) #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000571 0
Ezio Melotti35cbf162012-10-12 13:24:19 +0300572 >>> next(it) #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000573 1
Ezio Melotti35cbf162012-10-12 13:24:19 +0300574 >>> it.send(8) #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000575 8
Ezio Melotti35cbf162012-10-12 13:24:19 +0300576 >>> next(it) #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000577 9
Ezio Melotti35cbf162012-10-12 13:24:19 +0300578 >>> next(it) #doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000579 Traceback (most recent call last):
Georg Brandl1f01deb2009-01-03 22:47:39 +0000580 File "t.py", line 15, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000581 it.next()
Georg Brandl116aa622007-08-15 14:28:22 +0000582 StopIteration
583
584Because ``yield`` will often be returning ``None``, you should always check for
585this case. Don't just use its value in expressions unless you're sure that the
Ezio Melotti45a101d2012-10-12 12:42:51 +0300586:meth:`~generator.send` method will be the only method used resume your
587generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000588
Ezio Melotti45a101d2012-10-12 12:42:51 +0300589In addition to :meth:`~generator.send`, there are two other methods on
590generators:
Georg Brandl116aa622007-08-15 14:28:22 +0000591
Ezio Melotti45a101d2012-10-12 12:42:51 +0300592* :meth:`throw(type, value=None, traceback=None) <generator.throw>` is used to
593 raise an exception inside the generator; the exception is raised by the
594 ``yield`` expression where the generator's execution is paused.
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Ezio Melotti45a101d2012-10-12 12:42:51 +0300596* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the
597 generator to terminate the iteration. On receiving this exception, the
598 generator's code must either raise :exc:`GeneratorExit` or
599 :exc:`StopIteration`; catching the exception and doing anything else is
600 illegal and will trigger a :exc:`RuntimeError`. :meth:`~generator.close`
601 will also be called by Python's garbage collector when the generator is
602 garbage-collected.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604 If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
605 using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
606
607The cumulative effect of these changes is to turn generators from one-way
608producers of information into both producers and consumers.
609
610Generators also become **coroutines**, a more generalized form of subroutines.
611Subroutines are entered at one point and exited at another point (the top of the
612function, and a ``return`` statement), but coroutines can be entered, exited,
613and resumed at many different points (the ``yield`` statements).
614
615
616Built-in functions
617==================
618
619Let's look in more detail at built-in functions often used with iterators.
620
Georg Brandlf6945182008-02-01 11:56:49 +0000621Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
622features of generator expressions:
Georg Brandl116aa622007-08-15 14:28:22 +0000623
Ezio Melotti45a101d2012-10-12 12:42:51 +0300624:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence
Georg Brandlf6945182008-02-01 11:56:49 +0000625 ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
Georg Brandl116aa622007-08-15 14:28:22 +0000626
Christian Heimesfe337bf2008-03-23 21:54:12 +0000627 >>> def upper(s):
628 ... return s.upper()
Georg Brandl116aa622007-08-15 14:28:22 +0000629
Georg Brandla3deea12008-12-15 08:29:32 +0000630 >>> list(map(upper, ['sentence', 'fragment']))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000631 ['SENTENCE', 'FRAGMENT']
632 >>> [upper(s) for s in ['sentence', 'fragment']]
633 ['SENTENCE', 'FRAGMENT']
Georg Brandl116aa622007-08-15 14:28:22 +0000634
Georg Brandl48310cd2009-01-03 21:18:54 +0000635You can of course achieve the same effect with a list comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000636
Ezio Melotti45a101d2012-10-12 12:42:51 +0300637:func:`filter(predicate, iter) <filter>` returns an iterator over all the
638sequence elements that meet a certain condition, and is similarly duplicated by
639list comprehensions. A **predicate** is a function that returns the truth
640value of some condition; for use with :func:`filter`, the predicate must take a
641single value.
Georg Brandl116aa622007-08-15 14:28:22 +0000642
Christian Heimesfe337bf2008-03-23 21:54:12 +0000643 >>> def is_even(x):
644 ... return (x % 2) == 0
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Georg Brandla3deea12008-12-15 08:29:32 +0000646 >>> list(filter(is_even, range(10)))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000647 [0, 2, 4, 6, 8]
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Christian Heimesfe337bf2008-03-23 21:54:12 +0000650This can also be written as a list comprehension:
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Georg Brandlf6945182008-02-01 11:56:49 +0000652 >>> list(x for x in range(10) if is_even(x))
Georg Brandl116aa622007-08-15 14:28:22 +0000653 [0, 2, 4, 6, 8]
654
Georg Brandl116aa622007-08-15 14:28:22 +0000655
Ezio Melotti45a101d2012-10-12 12:42:51 +0300656:func:`enumerate(iter) <enumerate>` counts off the elements in the iterable,
657returning 2-tuples containing the count and each element. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Christian Heimesfe337bf2008-03-23 21:54:12 +0000659 >>> for item in enumerate(['subject', 'verb', 'object']):
Neal Norwitz752abd02008-05-13 04:55:24 +0000660 ... print(item)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000661 (0, 'subject')
662 (1, 'verb')
663 (2, 'object')
Georg Brandl116aa622007-08-15 14:28:22 +0000664
665:func:`enumerate` is often used when looping through a list and recording the
666indexes at which certain conditions are met::
667
668 f = open('data.txt', 'r')
669 for i, line in enumerate(f):
670 if line.strip() == '':
Georg Brandl6911e3c2007-09-04 07:15:32 +0000671 print('Blank line at line #%i' % i)
Georg Brandl116aa622007-08-15 14:28:22 +0000672
Ezio Melotti45a101d2012-10-12 12:42:51 +0300673:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the
674elements of the iterable into a list, sorts the list, and returns the sorted
675result. The *key*, and *reverse* arguments are passed through to the
676constructed list's :meth:`~list.sort` method. ::
Christian Heimesfe337bf2008-03-23 21:54:12 +0000677
678 >>> import random
679 >>> # Generate 8 random numbers between [0, 10000)
680 >>> rand_list = random.sample(range(10000), 8)
Ezio Melotti35cbf162012-10-12 13:24:19 +0300681 >>> rand_list #doctest: +SKIP
Christian Heimesfe337bf2008-03-23 21:54:12 +0000682 [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
Ezio Melotti35cbf162012-10-12 13:24:19 +0300683 >>> sorted(rand_list) #doctest: +SKIP
Christian Heimesfe337bf2008-03-23 21:54:12 +0000684 [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
Ezio Melotti35cbf162012-10-12 13:24:19 +0300685 >>> sorted(rand_list, reverse=True) #doctest: +SKIP
Christian Heimesfe337bf2008-03-23 21:54:12 +0000686 [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Ezio Melotti45a101d2012-10-12 12:42:51 +0300688(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Georg Brandl4216d2d2008-11-22 08:27:24 +0000690
Ezio Melotti45a101d2012-10-12 12:42:51 +0300691The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the
692truth values of an iterable's contents. :func:`any` returns True if any element
693in the iterable is a true value, and :func:`all` returns True if all of the
694elements are true values:
Georg Brandl116aa622007-08-15 14:28:22 +0000695
Christian Heimesfe337bf2008-03-23 21:54:12 +0000696 >>> any([0,1,0])
697 True
698 >>> any([0,0,0])
699 False
700 >>> any([1,1,1])
701 True
702 >>> all([0,1,0])
703 False
Georg Brandl48310cd2009-01-03 21:18:54 +0000704 >>> all([0,0,0])
Christian Heimesfe337bf2008-03-23 21:54:12 +0000705 False
706 >>> all([1,1,1])
707 True
Georg Brandl116aa622007-08-15 14:28:22 +0000708
709
Ezio Melotti45a101d2012-10-12 12:42:51 +0300710:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and
Georg Brandl4216d2d2008-11-22 08:27:24 +0000711returns them in a tuple::
Georg Brandl116aa622007-08-15 14:28:22 +0000712
Georg Brandl4216d2d2008-11-22 08:27:24 +0000713 zip(['a', 'b', 'c'], (1, 2, 3)) =>
714 ('a', 1), ('b', 2), ('c', 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Georg Brandl4216d2d2008-11-22 08:27:24 +0000716It doesn't construct an in-memory list and exhaust all the input iterators
717before returning; instead tuples are constructed and returned only if they're
718requested. (The technical term for this behaviour is `lazy evaluation
719<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Georg Brandl4216d2d2008-11-22 08:27:24 +0000721This iterator is intended to be used with iterables that are all of the same
722length. If the iterables are of different lengths, the resulting stream will be
723the same length as the shortest iterable. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Georg Brandl4216d2d2008-11-22 08:27:24 +0000725 zip(['a', 'b'], (1, 2, 3)) =>
726 ('a', 1), ('b', 2)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Georg Brandl4216d2d2008-11-22 08:27:24 +0000728You should avoid doing this, though, because an element may be taken from the
729longer iterators and discarded. This means you can't go on to use the iterators
730further because you risk skipping a discarded element.
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732
733The itertools module
734====================
735
736The :mod:`itertools` module contains a number of commonly-used iterators as well
737as functions for combining several iterators. This section will introduce the
738module's contents by showing small examples.
739
740The module's functions fall into a few broad classes:
741
742* Functions that create a new iterator based on an existing iterator.
743* Functions for treating an iterator's elements as function arguments.
744* Functions for selecting portions of an iterator's output.
745* A function for grouping an iterator's output.
746
747Creating new iterators
748----------------------
749
Ezio Melotti45a101d2012-10-12 12:42:51 +0300750:func:`itertools.count(n) <itertools.count>` returns an infinite stream of
751integers, increasing by 1 each time. You can optionally supply the starting
752number, which defaults to 0::
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Christian Heimesfe337bf2008-03-23 21:54:12 +0000754 itertools.count() =>
755 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
756 itertools.count(10) =>
757 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Ezio Melotti45a101d2012-10-12 12:42:51 +0300759:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of
760a provided iterable and returns a new iterator that returns its elements from
761first to last. The new iterator will repeat these elements infinitely. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Christian Heimesfe337bf2008-03-23 21:54:12 +0000763 itertools.cycle([1,2,3,4,5]) =>
764 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000765
Ezio Melotti45a101d2012-10-12 12:42:51 +0300766:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided
767element *n* times, or returns the element endlessly if *n* is not provided. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000768
769 itertools.repeat('abc') =>
770 abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
771 itertools.repeat('abc', 5) =>
772 abc, abc, abc, abc, abc
773
Ezio Melotti45a101d2012-10-12 12:42:51 +0300774:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary
775number of iterables as input, and returns all the elements of the first
776iterator, then all the elements of the second, and so on, until all of the
777iterables have been exhausted. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000778
779 itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
780 a, b, c, 1, 2, 3
781
Ezio Melotti45a101d2012-10-12 12:42:51 +0300782:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns
783a stream that's a slice of the iterator. With a single *stop* argument, it
784will return the first *stop* elements. If you supply a starting index, you'll
785get *stop-start* elements, and if you supply a value for *step*, elements
786will be skipped accordingly. Unlike Python's string and list slicing, you can't
787use negative values for *start*, *stop*, or *step*. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789 itertools.islice(range(10), 8) =>
790 0, 1, 2, 3, 4, 5, 6, 7
791 itertools.islice(range(10), 2, 8) =>
792 2, 3, 4, 5, 6, 7
793 itertools.islice(range(10), 2, 8, 2) =>
794 2, 4, 6
795
Ezio Melotti45a101d2012-10-12 12:42:51 +0300796:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it
797returns *n* independent iterators that will all return the contents of the
798source iterator.
799If you don't supply a value for *n*, the default is 2. Replicating iterators
Georg Brandl116aa622007-08-15 14:28:22 +0000800requires saving some of the contents of the source iterator, so this can consume
801significant memory if the iterator is large and one of the new iterators is
Christian Heimesfe337bf2008-03-23 21:54:12 +0000802consumed more than the others. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804 itertools.tee( itertools.count() ) =>
805 iterA, iterB
806
807 where iterA ->
808 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
809
810 and iterB ->
811 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
812
813
814Calling functions on elements
815-----------------------------
816
Ezio Melotti45a101d2012-10-12 12:42:51 +0300817The :mod:`operator` module contains a set of functions corresponding to Python's
818operators. Some examples are :func:`operator.add(a, b) <operator.add>` (adds
819two values), :func:`operator.ne(a, b) <operator.ne>` (same as ``a != b``), and
820:func:`operator.attrgetter('id') <operator.attrgetter>`
821(returns a callable that fetches the ``.id`` attribute).
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Ezio Melotti45a101d2012-10-12 12:42:51 +0300823:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the
824iterable will return a stream of tuples, and calls *func* using these tuples as
825the arguments::
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Georg Brandl48310cd2009-01-03 21:18:54 +0000827 itertools.starmap(os.path.join,
Ezio Melotti45a101d2012-10-12 12:42:51 +0300828 [('/bin', 'python'), ('/usr', 'bin', 'java'),
829 ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
Georg Brandl116aa622007-08-15 14:28:22 +0000830 =>
Ezio Melotti45a101d2012-10-12 12:42:51 +0300831 /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
834Selecting elements
835------------------
836
837Another group of functions chooses a subset of an iterator's elements based on a
838predicate.
839
Ezio Melotti45a101d2012-10-12 12:42:51 +0300840:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the
841opposite, returning all elements for which the predicate returns false::
Georg Brandl116aa622007-08-15 14:28:22 +0000842
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300846:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns
847elements for as long as the predicate returns true. Once the predicate returns
848false, the iterator will signal the end of its results. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850 def less_than_10(x):
Ezio Melotti45a101d2012-10-12 12:42:51 +0300851 return x < 10
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853 itertools.takewhile(less_than_10, itertools.count()) =>
854 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
855
856 itertools.takewhile(is_even, itertools.count()) =>
857 0
858
Ezio Melotti45a101d2012-10-12 12:42:51 +0300859:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards
860elements while the predicate returns true, and then returns the rest of the
861iterable's results. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863 itertools.dropwhile(less_than_10, itertools.count()) =>
864 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
865
866 itertools.dropwhile(is_even, itertools.count()) =>
867 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
868
869
870Grouping elements
871-----------------
872
Ezio Melotti45a101d2012-10-12 12:42:51 +0300873The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None)
874<itertools.groupby>`, is the most complicated. ``key_func(elem)`` is a function
875that can compute a key value for each element returned by the iterable. If you
876don't supply a key function, the key is simply each element itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Ezio Melotti45a101d2012-10-12 12:42:51 +0300878:func:`~itertools.groupby` collects all the consecutive elements from the
879underlying iterable that have the same key value, and returns a stream of
8802-tuples containing a key value and an iterator for the elements with that key.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
882::
883
Georg Brandl48310cd2009-01-03 21:18:54 +0000884 city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
Georg Brandl116aa622007-08-15 14:28:22 +0000885 ('Anchorage', 'AK'), ('Nome', 'AK'),
Georg Brandl48310cd2009-01-03 21:18:54 +0000886 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
Georg Brandl116aa622007-08-15 14:28:22 +0000887 ...
888 ]
889
Ezio Melotti45a101d2012-10-12 12:42:51 +0300890 def get_state(city_state):
Georg Brandl0df79792008-10-04 18:33:26 +0000891 return city_state[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000892
893 itertools.groupby(city_list, get_state) =>
894 ('AL', iterator-1),
895 ('AK', iterator-2),
896 ('AZ', iterator-3), ...
897
898 where
899 iterator-1 =>
900 ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
Georg Brandl48310cd2009-01-03 21:18:54 +0000901 iterator-2 =>
Georg Brandl116aa622007-08-15 14:28:22 +0000902 ('Anchorage', 'AK'), ('Nome', 'AK')
903 iterator-3 =>
904 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
905
Ezio Melotti45a101d2012-10-12 12:42:51 +0300906:func:`~itertools.groupby` assumes that the underlying iterable's contents will
907already be sorted based on the key. Note that the returned iterators also use
908the underlying iterable, so you have to consume the results of iterator-1 before
Georg Brandl116aa622007-08-15 14:28:22 +0000909requesting iterator-2 and its corresponding key.
910
911
912The functools module
913====================
914
915The :mod:`functools` module in Python 2.5 contains some higher-order functions.
916A **higher-order function** takes one or more functions as input and returns a
917new function. The most useful tool in this module is the
918:func:`functools.partial` function.
919
920For programs written in a functional style, you'll sometimes want to construct
921variants of existing functions that have some of the parameters filled in.
922Consider a Python function ``f(a, b, c)``; you may wish to create a new function
923``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
924one of ``f()``'s parameters. This is called "partial function application".
925
Ezio Melotti45a101d2012-10-12 12:42:51 +0300926The constructor for :func:`~functools.partial` takes the arguments
927``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The resulting
928object is callable, so you can just call it to invoke ``function`` with the
929filled-in arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000930
931Here's a small but realistic example::
932
933 import functools
934
Ezio Melotti45a101d2012-10-12 12:42:51 +0300935 def log(message, subsystem):
936 """Write the contents of 'message' to the specified subsystem."""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000937 print('%s: %s' % (subsystem, message))
Georg Brandl116aa622007-08-15 14:28:22 +0000938 ...
939
940 server_log = functools.partial(log, subsystem='server')
941 server_log('Unable to open socket')
942
Ezio Melotti45a101d2012-10-12 12:42:51 +0300943:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>`
944cumulatively performs an operation on all the iterable's elements and,
945therefore, can't be applied to infinite iterables. *func* must be a function
946that takes two elements and returns a single value. :func:`functools.reduce`
947takes the first two elements A and B returned by the iterator and calculates
948``func(A, B)``. It then requests the third element, C, calculates
949``func(func(A, B), C)``, combines this result with the fourth element returned,
950and continues until the iterable is exhausted. If the iterable returns no
951values at all, a :exc:`TypeError` exception is raised. If the initial value is
952supplied, it's used as a starting point and ``func(initial_value, A)`` is the
953first calculation. ::
Georg Brandl4216d2d2008-11-22 08:27:24 +0000954
955 >>> import operator, functools
956 >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
957 'ABBC'
958 >>> functools.reduce(operator.concat, [])
959 Traceback (most recent call last):
960 ...
961 TypeError: reduce() of empty sequence with no initial value
962 >>> functools.reduce(operator.mul, [1,2,3], 1)
963 6
964 >>> functools.reduce(operator.mul, [], 1)
965 1
966
967If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the
968elements of the iterable. This case is so common that there's a special
969built-in called :func:`sum` to compute it:
970
971 >>> import functools
972 >>> functools.reduce(operator.add, [1,2,3,4], 0)
973 10
974 >>> sum([1,2,3,4])
975 10
976 >>> sum([])
977 0
978
Ezio Melotti45a101d2012-10-12 12:42:51 +0300979For many uses of :func:`functools.reduce`, though, it can be clearer to just
980write the obvious :keyword:`for` loop::
Georg Brandl4216d2d2008-11-22 08:27:24 +0000981
982 import functools
983 # Instead of:
984 product = functools.reduce(operator.mul, [1,2,3], 1)
985
986 # You can write:
987 product = 1
988 for i in [1,2,3]:
989 product *= i
990
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992The operator module
993-------------------
994
995The :mod:`operator` module was mentioned earlier. It contains a set of
996functions corresponding to Python's operators. These functions are often useful
997in functional-style code because they save you from writing trivial functions
998that perform a single operation.
999
1000Some of the functions in this module are:
1001
Georg Brandlf6945182008-02-01 11:56:49 +00001002* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ...
Georg Brandl116aa622007-08-15 14:28:22 +00001003* Logical operations: ``not_()``, ``truth()``.
1004* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1005* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1006* Object identity: ``is_()``, ``is_not()``.
1007
1008Consult the operator module's documentation for a complete list.
1009
1010
Georg Brandl4216d2d2008-11-22 08:27:24 +00001011Small functions and the lambda expression
1012=========================================
1013
1014When writing functional-style programs, you'll often need little functions that
1015act as predicates or that combine elements in some way.
1016
1017If there's a Python built-in or a module function that's suitable, you don't
1018need to define a new function at all::
1019
1020 stripped_lines = [line.strip() for line in lines]
1021 existing_files = filter(os.path.exists, file_list)
1022
1023If the function you need doesn't exist, you need to write it. One way to write
Ezio Melotti45a101d2012-10-12 12:42:51 +03001024small functions is to use the :keyword:`lambda` statement. ``lambda`` takes a
1025number of parameters and an expression combining these parameters, and creates
1026an anonymous function that returns the value of the expression::
Georg Brandl4216d2d2008-11-22 08:27:24 +00001027
1028 adder = lambda x, y: x+y
1029
Ezio Melotti45a101d2012-10-12 12:42:51 +03001030 print_assign = lambda name, value: name + '=' + str(value)
1031
Georg Brandl4216d2d2008-11-22 08:27:24 +00001032An alternative is to just use the ``def`` statement and define a function in the
1033usual way::
1034
Ezio Melotti45a101d2012-10-12 12:42:51 +03001035 def adder(x, y):
1036 return x + y
Georg Brandl4216d2d2008-11-22 08:27:24 +00001037
1038 def print_assign(name, value):
1039 return name + '=' + str(value)
1040
Georg Brandl4216d2d2008-11-22 08:27:24 +00001041Which alternative is preferable? That's a style question; my usual course is to
1042avoid using ``lambda``.
1043
1044One reason for my preference is that ``lambda`` is quite limited in the
1045functions it can define. The result has to be computable as a single
1046expression, which means you can't have multiway ``if... elif... else``
1047comparisons or ``try... except`` statements. If you try to do too much in a
1048``lambda`` statement, you'll end up with an overly complicated expression that's
Ezio Melotti45a101d2012-10-12 12:42:51 +03001049hard to read. Quick, what's the following code doing? ::
Georg Brandl4216d2d2008-11-22 08:27:24 +00001050
1051 import functools
1052 total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
1053
1054You can figure it out, but it takes time to disentangle the expression to figure
1055out what's going on. Using a short nested ``def`` statements makes things a
1056little bit better::
1057
1058 import functools
Ezio Melotti45a101d2012-10-12 12:42:51 +03001059 def combine(a, b):
Georg Brandl4216d2d2008-11-22 08:27:24 +00001060 return 0, a[1] + b[1]
1061
1062 total = functools.reduce(combine, items)[1]
1063
1064But it would be best of all if I had simply used a ``for`` loop::
1065
1066 total = 0
1067 for a, b in items:
1068 total += b
1069
1070Or the :func:`sum` built-in and a generator expression::
1071
1072 total = sum(b for a,b in items)
1073
1074Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops.
1075
1076Fredrik Lundh once suggested the following set of rules for refactoring uses of
1077``lambda``:
1078
Ezio Melotti45a101d2012-10-12 12:42:51 +030010791. Write a lambda function.
10802. Write a comment explaining what the heck that lambda does.
10813. Study the comment for a while, and think of a name that captures the essence
Georg Brandl4216d2d2008-11-22 08:27:24 +00001082 of the comment.
Ezio Melotti45a101d2012-10-12 12:42:51 +030010834. Convert the lambda to a def statement, using that name.
10845. Remove the comment.
Georg Brandl4216d2d2008-11-22 08:27:24 +00001085
Georg Brandl48310cd2009-01-03 21:18:54 +00001086I really like these rules, but you're free to disagree
Georg Brandl4216d2d2008-11-22 08:27:24 +00001087about whether this lambda-free style is better.
1088
1089
Georg Brandl116aa622007-08-15 14:28:22 +00001090Revision History and Acknowledgements
1091=====================================
1092
1093The author would like to thank the following people for offering suggestions,
1094corrections and assistance with various drafts of this article: Ian Bicking,
1095Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1096Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1097
1098Version 0.1: posted June 30 2006.
1099
1100Version 0.11: posted July 1 2006. Typo fixes.
1101
1102Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one.
1103Typo fixes.
1104
1105Version 0.21: Added more references suggested on the tutor mailing list.
1106
1107Version 0.30: Adds a section on the ``functional`` module written by Collin
1108Winter; adds short section on the operator module; a few other edits.
1109
1110
1111References
1112==========
1113
1114General
1115-------
1116
1117**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1118Gerald Jay Sussman with Julie Sussman. Full text at
1119http://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
1120chapters 2 and 3 discuss the use of sequences and streams to organize the data
1121flow inside a program. The book uses Scheme for its examples, but many of the
1122design approaches described in these chapters are applicable to functional-style
1123Python code.
1124
1125http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1126programming that uses Java examples and has a lengthy historical introduction.
1127
1128http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1129describing functional programming.
1130
1131http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1132
1133http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1134
1135Python-specific
1136---------------
1137
1138http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1139:title-reference:`Text Processing in Python` discusses functional programming
1140for text processing, in the section titled "Utilizing Higher-Order Functions in
1141Text Processing".
1142
1143Mertz also wrote a 3-part series of articles on functional programming
Georg Brandl48310cd2009-01-03 21:18:54 +00001144for IBM's DeveloperWorks site; see
Sandro Tosi1abde362011-12-31 18:46:50 +01001145`part 1 <http://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
1146`part 2 <http://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
1147`part 3 <http://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,
Georg Brandl116aa622007-08-15 14:28:22 +00001148
1149
1150Python documentation
1151--------------------
1152
1153Documentation for the :mod:`itertools` module.
1154
1155Documentation for the :mod:`operator` module.
1156
1157:pep:`289`: "Generator Expressions"
1158
1159:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1160features in Python 2.5.
1161
1162.. comment
1163
1164 Topics to place
1165 -----------------------------
1166
1167 XXX os.walk()
1168
1169 XXX Need a large example.
1170
1171 But will an example add much? I'll post a first draft and see
1172 what the comments say.
1173
1174.. comment
1175
1176 Original outline:
1177 Introduction
1178 Idea of FP
1179 Programs built out of functions
1180 Functions are strictly input-output, no internal state
1181 Opposed to OO programming, where objects have state
1182
1183 Why FP?
1184 Formal provability
1185 Assignment is difficult to reason about
1186 Not very relevant to Python
1187 Modularity
1188 Small functions that do one thing
1189 Debuggability:
1190 Easy to test due to lack of state
1191 Easy to verify output from intermediate steps
1192 Composability
1193 You assemble a toolbox of functions that can be mixed
1194
1195 Tackling a problem
1196 Need a significant example
1197
1198 Iterators
1199 Generators
1200 The itertools module
1201 List comprehensions
1202 Small functions and the lambda statement
1203 Built-in functions
1204 map
1205 filter
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207.. comment
1208
1209 Handy little function for printing part of an iterator -- used
1210 while writing this document.
1211
1212 import itertools
1213 def print_iter(it):
1214 slice = itertools.islice(it, 10)
1215 for elem in slice[:-1]:
1216 sys.stdout.write(str(elem))
1217 sys.stdout.write(', ')
Georg Brandl6911e3c2007-09-04 07:15:32 +00001218 print(elem[-1])
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220