blob: 8eadb01c68fc36f338c1802d3d2f65f5104d2992 [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)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000201 >>> it
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
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300299:meth:`~dict.values` or :meth:`~dict.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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300308Files also support iteration by calling the :meth:`~io.TextIOBase.readline`
309method until there are no more lines in the file. This means you can read each
310line of a file like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000311
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 Melotti19192dd2010-04-05 13:25:51 +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)
Ezio Melotti45a101d2012-10-12 12:42:51 +0300418 >>> [(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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300428 [x, y for x in seq1 for y in seq2]
Georg Brandl116aa622007-08-15 14:28:22 +0000429 # Correct
Ezio Melotti45a101d2012-10-12 12:42:51 +0300430 [(x, y) for x in seq1 for y in seq2]
Georg Brandl116aa622007-08-15 14:28:22 +0000431
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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300457Any function containing a :keyword:`yield` keyword is a generator function;
458this is detected by Python's :term:`bytecode` compiler which compiles the
459function specially 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
Ezio Melotti45a101d2012-10-12 12:42:51 +0300467generator's :meth:`~generator.__next__` method, the function will resume
468executing.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Christian Heimesfe337bf2008-03-23 21:54:12 +0000470Here's a sample usage of the ``generate_ints()`` generator:
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472 >>> gen = generate_ints(3)
473 >>> gen
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000474 <generator object generate_ints at ...>
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000475 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000476 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000477 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000478 1
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000479 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000480 2
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000481 >>> next(gen)
Georg Brandl116aa622007-08-15 14:28:22 +0000482 Traceback (most recent call last):
483 File "stdin", line 1, in ?
484 File "stdin", line 2, in generate_ints
485 StopIteration
486
487You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
488generate_ints(3)``.
489
490Inside a generator function, the ``return`` statement can only be used without a
491value, and signals the end of the procession of values; after executing a
492``return`` the generator cannot return any further values. ``return`` with a
493value, such as ``return 5``, is a syntax error inside a generator function. The
494end of the generator's results can also be indicated by raising
Ezio Melotti45a101d2012-10-12 12:42:51 +0300495:exc:`StopIteration` manually, or by just letting the flow of execution fall off
Georg Brandl116aa622007-08-15 14:28:22 +0000496the bottom of the function.
497
498You could achieve the effect of generators manually by writing your own class
499and storing all the local variables of the generator as instance variables. For
500example, returning a list of integers could be done by setting ``self.count`` to
Ezio Melotti45a101d2012-10-12 12:42:51 +03005010, and having the :meth:`~iterator.__next__` method increment ``self.count`` and
502return it.
Georg Brandl116aa622007-08-15 14:28:22 +0000503However, for a moderately complicated generator, writing a corresponding class
504can be much messier.
505
Ezio Melotti45a101d2012-10-12 12:42:51 +0300506The test suite included with Python's library,
507:source:`Lib/test/test_generators.py`, contains
Georg Brandl116aa622007-08-15 14:28:22 +0000508a number of more interesting examples. Here's one generator that implements an
Christian Heimesfe337bf2008-03-23 21:54:12 +0000509in-order traversal of a tree using generators recursively. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511 # A recursive generator that generates Tree leaves in in-order.
512 def inorder(t):
513 if t:
514 for x in inorder(t.left):
515 yield x
516
517 yield t.label
518
519 for x in inorder(t.right):
520 yield x
521
522Two other examples in ``test_generators.py`` produce solutions for the N-Queens
523problem (placing N queens on an NxN chess board so that no queen threatens
524another) and the Knight's Tour (finding a route that takes a knight to every
525square of an NxN chessboard without visiting any square twice).
526
527
528
529Passing values into a generator
530-------------------------------
531
532In Python 2.4 and earlier, generators only produced output. Once a generator's
533code was invoked to create an iterator, there was no way to pass any new
534information into the function when its execution is resumed. You could hack
535together this ability by making the generator look at a global variable or by
536passing in some mutable object that callers then modify, but these approaches
537are messy.
538
539In Python 2.5 there's a simple way to pass values into a generator.
540:keyword:`yield` became an expression, returning a value that can be assigned to
541a variable or otherwise operated on::
542
543 val = (yield i)
544
545I recommend that you **always** put parentheses around a ``yield`` expression
546when you're doing something with the returned value, as in the above example.
547The parentheses aren't always necessary, but it's easier to always add them
548instead of having to remember when they're needed.
549
Ezio Melotti45a101d2012-10-12 12:42:51 +0300550(:pep:`342` explains the exact rules, which are that a ``yield``-expression must
Georg Brandl116aa622007-08-15 14:28:22 +0000551always be parenthesized except when it occurs at the top-level expression on the
552right-hand side of an assignment. This means you can write ``val = yield i``
553but have to use parentheses when there's an operation, as in ``val = (yield i)
554+ 12``.)
555
Ezio Melotti45a101d2012-10-12 12:42:51 +0300556Values are sent into a generator by calling its :meth:`send(value)
557<generator.send>` method. This method resumes the generator's code and the
558``yield`` expression returns the specified value. If the regular
559:meth:`~generator.__next__` method is called, the ``yield`` returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561Here's a simple counter that increments by 1 and allows changing the value of
562the internal counter.
563
Christian Heimesfe337bf2008-03-23 21:54:12 +0000564.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +0000565
Ezio Melotti45a101d2012-10-12 12:42:51 +0300566 def counter(maximum):
Georg Brandl116aa622007-08-15 14:28:22 +0000567 i = 0
568 while i < maximum:
569 val = (yield i)
570 # If value provided, change counter
571 if val is not None:
572 i = val
573 else:
574 i += 1
575
576And here's an example of changing the counter:
577
578 >>> it = counter(10)
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000579 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000580 0
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000581 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000582 1
Georg Brandl6911e3c2007-09-04 07:15:32 +0000583 >>> it.send(8)
Georg Brandl116aa622007-08-15 14:28:22 +0000584 8
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000585 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000586 9
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000587 >>> next(it)
Georg Brandl116aa622007-08-15 14:28:22 +0000588 Traceback (most recent call last):
Georg Brandl1f01deb2009-01-03 22:47:39 +0000589 File "t.py", line 15, in ?
Georg Brandl6911e3c2007-09-04 07:15:32 +0000590 it.next()
Georg Brandl116aa622007-08-15 14:28:22 +0000591 StopIteration
592
593Because ``yield`` will often be returning ``None``, you should always check for
594this case. Don't just use its value in expressions unless you're sure that the
Ezio Melotti45a101d2012-10-12 12:42:51 +0300595:meth:`~generator.send` method will be the only method used resume your
596generator function.
Georg Brandl116aa622007-08-15 14:28:22 +0000597
Ezio Melotti45a101d2012-10-12 12:42:51 +0300598In addition to :meth:`~generator.send`, there are two other methods on
599generators:
Georg Brandl116aa622007-08-15 14:28:22 +0000600
Ezio Melotti45a101d2012-10-12 12:42:51 +0300601* :meth:`throw(type, value=None, traceback=None) <generator.throw>` is used to
602 raise an exception inside the generator; the exception is raised by the
603 ``yield`` expression where the generator's execution is paused.
Georg Brandl116aa622007-08-15 14:28:22 +0000604
Ezio Melotti45a101d2012-10-12 12:42:51 +0300605* :meth:`~generator.close` raises a :exc:`GeneratorExit` exception inside the
606 generator to terminate the iteration. On receiving this exception, the
607 generator's code must either raise :exc:`GeneratorExit` or
608 :exc:`StopIteration`; catching the exception and doing anything else is
609 illegal and will trigger a :exc:`RuntimeError`. :meth:`~generator.close`
610 will also be called by Python's garbage collector when the generator is
611 garbage-collected.
Georg Brandl116aa622007-08-15 14:28:22 +0000612
613 If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
614 using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.
615
616The cumulative effect of these changes is to turn generators from one-way
617producers of information into both producers and consumers.
618
619Generators also become **coroutines**, a more generalized form of subroutines.
620Subroutines are entered at one point and exited at another point (the top of the
621function, and a ``return`` statement), but coroutines can be entered, exited,
622and resumed at many different points (the ``yield`` statements).
623
624
625Built-in functions
626==================
627
628Let's look in more detail at built-in functions often used with iterators.
629
Georg Brandlf6945182008-02-01 11:56:49 +0000630Two of Python's built-in functions, :func:`map` and :func:`filter` duplicate the
631features of generator expressions:
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Ezio Melotti45a101d2012-10-12 12:42:51 +0300633:func:`map(f, iterA, iterB, ...) <map>` returns an iterator over the sequence
Georg Brandlf6945182008-02-01 11:56:49 +0000634 ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Christian Heimesfe337bf2008-03-23 21:54:12 +0000636 >>> def upper(s):
637 ... return s.upper()
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Georg Brandla3deea12008-12-15 08:29:32 +0000639 >>> list(map(upper, ['sentence', 'fragment']))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000640 ['SENTENCE', 'FRAGMENT']
641 >>> [upper(s) for s in ['sentence', 'fragment']]
642 ['SENTENCE', 'FRAGMENT']
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Georg Brandl48310cd2009-01-03 21:18:54 +0000644You can of course achieve the same effect with a list comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Ezio Melotti45a101d2012-10-12 12:42:51 +0300646:func:`filter(predicate, iter) <filter>` returns an iterator over all the
647sequence elements that meet a certain condition, and is similarly duplicated by
648list comprehensions. A **predicate** is a function that returns the truth
649value of some condition; for use with :func:`filter`, the predicate must take a
650single value.
Georg Brandl116aa622007-08-15 14:28:22 +0000651
Christian Heimesfe337bf2008-03-23 21:54:12 +0000652 >>> def is_even(x):
653 ... return (x % 2) == 0
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Georg Brandla3deea12008-12-15 08:29:32 +0000655 >>> list(filter(is_even, range(10)))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000656 [0, 2, 4, 6, 8]
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Christian Heimesfe337bf2008-03-23 21:54:12 +0000659This can also be written as a list comprehension:
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Georg Brandlf6945182008-02-01 11:56:49 +0000661 >>> list(x for x in range(10) if is_even(x))
Georg Brandl116aa622007-08-15 14:28:22 +0000662 [0, 2, 4, 6, 8]
663
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Ezio Melotti45a101d2012-10-12 12:42:51 +0300665:func:`enumerate(iter) <enumerate>` counts off the elements in the iterable,
666returning 2-tuples containing the count and each element. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Christian Heimesfe337bf2008-03-23 21:54:12 +0000668 >>> for item in enumerate(['subject', 'verb', 'object']):
Neal Norwitz752abd02008-05-13 04:55:24 +0000669 ... print(item)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000670 (0, 'subject')
671 (1, 'verb')
672 (2, 'object')
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674:func:`enumerate` is often used when looping through a list and recording the
675indexes at which certain conditions are met::
676
677 f = open('data.txt', 'r')
678 for i, line in enumerate(f):
679 if line.strip() == '':
Georg Brandl6911e3c2007-09-04 07:15:32 +0000680 print('Blank line at line #%i' % i)
Georg Brandl116aa622007-08-15 14:28:22 +0000681
Ezio Melotti45a101d2012-10-12 12:42:51 +0300682:func:`sorted(iterable, key=None, reverse=False) <sorted>` collects all the
683elements of the iterable into a list, sorts the list, and returns the sorted
684result. The *key*, and *reverse* arguments are passed through to the
685constructed list's :meth:`~list.sort` method. ::
Christian Heimesfe337bf2008-03-23 21:54:12 +0000686
687 >>> import random
688 >>> # Generate 8 random numbers between [0, 10000)
689 >>> rand_list = random.sample(range(10000), 8)
690 >>> rand_list
691 [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
692 >>> sorted(rand_list)
693 [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
694 >>> sorted(rand_list, reverse=True)
695 [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Ezio Melotti45a101d2012-10-12 12:42:51 +0300697(For a more detailed discussion of sorting, see the :ref:`sortinghowto`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Georg Brandl4216d2d2008-11-22 08:27:24 +0000699
Ezio Melotti45a101d2012-10-12 12:42:51 +0300700The :func:`any(iter) <any>` and :func:`all(iter) <all>` built-ins look at the
701truth values of an iterable's contents. :func:`any` returns True if any element
702in the iterable is a true value, and :func:`all` returns True if all of the
703elements are true values:
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Christian Heimesfe337bf2008-03-23 21:54:12 +0000705 >>> any([0,1,0])
706 True
707 >>> any([0,0,0])
708 False
709 >>> any([1,1,1])
710 True
711 >>> all([0,1,0])
712 False
Georg Brandl48310cd2009-01-03 21:18:54 +0000713 >>> all([0,0,0])
Christian Heimesfe337bf2008-03-23 21:54:12 +0000714 False
715 >>> all([1,1,1])
716 True
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718
Ezio Melotti45a101d2012-10-12 12:42:51 +0300719:func:`zip(iterA, iterB, ...) <zip>` takes one element from each iterable and
Georg Brandl4216d2d2008-11-22 08:27:24 +0000720returns them in a tuple::
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Georg Brandl4216d2d2008-11-22 08:27:24 +0000722 zip(['a', 'b', 'c'], (1, 2, 3)) =>
723 ('a', 1), ('b', 2), ('c', 3)
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Georg Brandl4216d2d2008-11-22 08:27:24 +0000725It doesn't construct an in-memory list and exhaust all the input iterators
726before returning; instead tuples are constructed and returned only if they're
727requested. (The technical term for this behaviour is `lazy evaluation
728<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl4216d2d2008-11-22 08:27:24 +0000730This iterator is intended to be used with iterables that are all of the same
731length. If the iterables are of different lengths, the resulting stream will be
732the same length as the shortest iterable. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandl4216d2d2008-11-22 08:27:24 +0000734 zip(['a', 'b'], (1, 2, 3)) =>
735 ('a', 1), ('b', 2)
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Georg Brandl4216d2d2008-11-22 08:27:24 +0000737You should avoid doing this, though, because an element may be taken from the
738longer iterators and discarded. This means you can't go on to use the iterators
739further because you risk skipping a discarded element.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742The itertools module
743====================
744
745The :mod:`itertools` module contains a number of commonly-used iterators as well
746as functions for combining several iterators. This section will introduce the
747module's contents by showing small examples.
748
749The module's functions fall into a few broad classes:
750
751* Functions that create a new iterator based on an existing iterator.
752* Functions for treating an iterator's elements as function arguments.
753* Functions for selecting portions of an iterator's output.
754* A function for grouping an iterator's output.
755
756Creating new iterators
757----------------------
758
Ezio Melotti45a101d2012-10-12 12:42:51 +0300759:func:`itertools.count(n) <itertools.count>` returns an infinite stream of
760integers, increasing by 1 each time. You can optionally supply the starting
761number, which defaults to 0::
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Christian Heimesfe337bf2008-03-23 21:54:12 +0000763 itertools.count() =>
764 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
765 itertools.count(10) =>
766 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Ezio Melotti45a101d2012-10-12 12:42:51 +0300768:func:`itertools.cycle(iter) <itertools.cycle>` saves a copy of the contents of
769a provided iterable and returns a new iterator that returns its elements from
770first to last. The new iterator will repeat these elements infinitely. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000771
Christian Heimesfe337bf2008-03-23 21:54:12 +0000772 itertools.cycle([1,2,3,4,5]) =>
773 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
Georg Brandl116aa622007-08-15 14:28:22 +0000774
Ezio Melotti45a101d2012-10-12 12:42:51 +0300775:func:`itertools.repeat(elem, [n]) <itertools.repeat>` returns the provided
776element *n* times, or returns the element endlessly if *n* is not provided. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778 itertools.repeat('abc') =>
779 abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
780 itertools.repeat('abc', 5) =>
781 abc, abc, abc, abc, abc
782
Ezio Melotti45a101d2012-10-12 12:42:51 +0300783:func:`itertools.chain(iterA, iterB, ...) <itertools.chain>` takes an arbitrary
784number of iterables as input, and returns all the elements of the first
785iterator, then all the elements of the second, and so on, until all of the
786iterables have been exhausted. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788 itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
789 a, b, c, 1, 2, 3
790
Ezio Melotti45a101d2012-10-12 12:42:51 +0300791:func:`itertools.islice(iter, [start], stop, [step]) <itertools.islice>` returns
792a stream that's a slice of the iterator. With a single *stop* argument, it
793will return the first *stop* elements. If you supply a starting index, you'll
794get *stop-start* elements, and if you supply a value for *step*, elements
795will be skipped accordingly. Unlike Python's string and list slicing, you can't
796use negative values for *start*, *stop*, or *step*. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000797
798 itertools.islice(range(10), 8) =>
799 0, 1, 2, 3, 4, 5, 6, 7
800 itertools.islice(range(10), 2, 8) =>
801 2, 3, 4, 5, 6, 7
802 itertools.islice(range(10), 2, 8, 2) =>
803 2, 4, 6
804
Ezio Melotti45a101d2012-10-12 12:42:51 +0300805:func:`itertools.tee(iter, [n]) <itertools.tee>` replicates an iterator; it
806returns *n* independent iterators that will all return the contents of the
807source iterator.
808If you don't supply a value for *n*, the default is 2. Replicating iterators
Georg Brandl116aa622007-08-15 14:28:22 +0000809requires saving some of the contents of the source iterator, so this can consume
810significant memory if the iterator is large and one of the new iterators is
Christian Heimesfe337bf2008-03-23 21:54:12 +0000811consumed more than the others. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813 itertools.tee( itertools.count() ) =>
814 iterA, iterB
815
816 where iterA ->
817 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
818
819 and iterB ->
820 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
821
822
823Calling functions on elements
824-----------------------------
825
Ezio Melotti45a101d2012-10-12 12:42:51 +0300826The :mod:`operator` module contains a set of functions corresponding to Python's
827operators. Some examples are :func:`operator.add(a, b) <operator.add>` (adds
828two values), :func:`operator.ne(a, b) <operator.ne>` (same as ``a != b``), and
829:func:`operator.attrgetter('id') <operator.attrgetter>`
830(returns a callable that fetches the ``.id`` attribute).
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Ezio Melotti45a101d2012-10-12 12:42:51 +0300832:func:`itertools.starmap(func, iter) <itertools.starmap>` assumes that the
833iterable will return a stream of tuples, and calls *func* using these tuples as
834the arguments::
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandl48310cd2009-01-03 21:18:54 +0000836 itertools.starmap(os.path.join,
Ezio Melotti45a101d2012-10-12 12:42:51 +0300837 [('/bin', 'python'), ('/usr', 'bin', 'java'),
838 ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
Georg Brandl116aa622007-08-15 14:28:22 +0000839 =>
Ezio Melotti45a101d2012-10-12 12:42:51 +0300840 /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842
843Selecting elements
844------------------
845
846Another group of functions chooses a subset of an iterator's elements based on a
847predicate.
848
Ezio Melotti45a101d2012-10-12 12:42:51 +0300849:func:`itertools.filterfalse(predicate, iter) <itertools.filterfalse>` is the
850opposite, returning all elements for which the predicate returns false::
Georg Brandl116aa622007-08-15 14:28:22 +0000851
Georg Brandl4216d2d2008-11-22 08:27:24 +0000852 itertools.filterfalse(is_even, itertools.count()) =>
Georg Brandl116aa622007-08-15 14:28:22 +0000853 1, 3, 5, 7, 9, 11, 13, 15, ...
854
Ezio Melotti45a101d2012-10-12 12:42:51 +0300855:func:`itertools.takewhile(predicate, iter) <itertools.takewhile>` returns
856elements for as long as the predicate returns true. Once the predicate returns
857false, the iterator will signal the end of its results. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859 def less_than_10(x):
Ezio Melotti45a101d2012-10-12 12:42:51 +0300860 return x < 10
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862 itertools.takewhile(less_than_10, itertools.count()) =>
863 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
864
865 itertools.takewhile(is_even, itertools.count()) =>
866 0
867
Ezio Melotti45a101d2012-10-12 12:42:51 +0300868:func:`itertools.dropwhile(predicate, iter) <itertools.dropwhile>` discards
869elements while the predicate returns true, and then returns the rest of the
870iterable's results. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000871
872 itertools.dropwhile(less_than_10, itertools.count()) =>
873 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
874
875 itertools.dropwhile(is_even, itertools.count()) =>
876 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
877
878
879Grouping elements
880-----------------
881
Ezio Melotti45a101d2012-10-12 12:42:51 +0300882The last function I'll discuss, :func:`itertools.groupby(iter, key_func=None)
883<itertools.groupby>`, is the most complicated. ``key_func(elem)`` is a function
884that can compute a key value for each element returned by the iterable. If you
885don't supply a key function, the key is simply each element itself.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Ezio Melotti45a101d2012-10-12 12:42:51 +0300887:func:`~itertools.groupby` collects all the consecutive elements from the
888underlying iterable that have the same key value, and returns a stream of
8892-tuples containing a key value and an iterator for the elements with that key.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891::
892
Georg Brandl48310cd2009-01-03 21:18:54 +0000893 city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
Georg Brandl116aa622007-08-15 14:28:22 +0000894 ('Anchorage', 'AK'), ('Nome', 'AK'),
Georg Brandl48310cd2009-01-03 21:18:54 +0000895 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
Georg Brandl116aa622007-08-15 14:28:22 +0000896 ...
897 ]
898
Ezio Melotti45a101d2012-10-12 12:42:51 +0300899 def get_state(city_state):
Georg Brandl0df79792008-10-04 18:33:26 +0000900 return city_state[1]
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902 itertools.groupby(city_list, get_state) =>
903 ('AL', iterator-1),
904 ('AK', iterator-2),
905 ('AZ', iterator-3), ...
906
907 where
908 iterator-1 =>
909 ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
Georg Brandl48310cd2009-01-03 21:18:54 +0000910 iterator-2 =>
Georg Brandl116aa622007-08-15 14:28:22 +0000911 ('Anchorage', 'AK'), ('Nome', 'AK')
912 iterator-3 =>
913 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
914
Ezio Melotti45a101d2012-10-12 12:42:51 +0300915:func:`~itertools.groupby` assumes that the underlying iterable's contents will
916already be sorted based on the key. Note that the returned iterators also use
917the underlying iterable, so you have to consume the results of iterator-1 before
Georg Brandl116aa622007-08-15 14:28:22 +0000918requesting iterator-2 and its corresponding key.
919
920
921The functools module
922====================
923
924The :mod:`functools` module in Python 2.5 contains some higher-order functions.
925A **higher-order function** takes one or more functions as input and returns a
926new function. The most useful tool in this module is the
927:func:`functools.partial` function.
928
929For programs written in a functional style, you'll sometimes want to construct
930variants of existing functions that have some of the parameters filled in.
931Consider a Python function ``f(a, b, c)``; you may wish to create a new function
932``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
933one of ``f()``'s parameters. This is called "partial function application".
934
Ezio Melotti45a101d2012-10-12 12:42:51 +0300935The constructor for :func:`~functools.partial` takes the arguments
936``(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)``. The resulting
937object is callable, so you can just call it to invoke ``function`` with the
938filled-in arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940Here's a small but realistic example::
941
942 import functools
943
Ezio Melotti45a101d2012-10-12 12:42:51 +0300944 def log(message, subsystem):
945 """Write the contents of 'message' to the specified subsystem."""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000946 print('%s: %s' % (subsystem, message))
Georg Brandl116aa622007-08-15 14:28:22 +0000947 ...
948
949 server_log = functools.partial(log, subsystem='server')
950 server_log('Unable to open socket')
951
Ezio Melotti45a101d2012-10-12 12:42:51 +0300952:func:`functools.reduce(func, iter, [initial_value]) <functools.reduce>`
953cumulatively performs an operation on all the iterable's elements and,
954therefore, can't be applied to infinite iterables. *func* must be a function
955that takes two elements and returns a single value. :func:`functools.reduce`
956takes the first two elements A and B returned by the iterator and calculates
957``func(A, B)``. It then requests the third element, C, calculates
958``func(func(A, B), C)``, combines this result with the fourth element returned,
959and continues until the iterable is exhausted. If the iterable returns no
960values at all, a :exc:`TypeError` exception is raised. If the initial value is
961supplied, it's used as a starting point and ``func(initial_value, A)`` is the
962first calculation. ::
Georg Brandl4216d2d2008-11-22 08:27:24 +0000963
964 >>> import operator, functools
965 >>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
966 'ABBC'
967 >>> functools.reduce(operator.concat, [])
968 Traceback (most recent call last):
969 ...
970 TypeError: reduce() of empty sequence with no initial value
971 >>> functools.reduce(operator.mul, [1,2,3], 1)
972 6
973 >>> functools.reduce(operator.mul, [], 1)
974 1
975
976If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all the
977elements of the iterable. This case is so common that there's a special
978built-in called :func:`sum` to compute it:
979
980 >>> import functools
981 >>> functools.reduce(operator.add, [1,2,3,4], 0)
982 10
983 >>> sum([1,2,3,4])
984 10
985 >>> sum([])
986 0
987
Ezio Melotti45a101d2012-10-12 12:42:51 +0300988For many uses of :func:`functools.reduce`, though, it can be clearer to just
989write the obvious :keyword:`for` loop::
Georg Brandl4216d2d2008-11-22 08:27:24 +0000990
991 import functools
992 # Instead of:
993 product = functools.reduce(operator.mul, [1,2,3], 1)
994
995 # You can write:
996 product = 1
997 for i in [1,2,3]:
998 product *= i
999
Georg Brandl116aa622007-08-15 14:28:22 +00001000
1001The operator module
1002-------------------
1003
1004The :mod:`operator` module was mentioned earlier. It contains a set of
1005functions corresponding to Python's operators. These functions are often useful
1006in functional-style code because they save you from writing trivial functions
1007that perform a single operation.
1008
1009Some of the functions in this module are:
1010
Georg Brandlf6945182008-02-01 11:56:49 +00001011* Math operations: ``add()``, ``sub()``, ``mul()``, ``floordiv()``, ``abs()``, ...
Georg Brandl116aa622007-08-15 14:28:22 +00001012* Logical operations: ``not_()``, ``truth()``.
1013* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
1014* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
1015* Object identity: ``is_()``, ``is_not()``.
1016
1017Consult the operator module's documentation for a complete list.
1018
1019
Georg Brandl4216d2d2008-11-22 08:27:24 +00001020Small functions and the lambda expression
1021=========================================
1022
1023When writing functional-style programs, you'll often need little functions that
1024act as predicates or that combine elements in some way.
1025
1026If there's a Python built-in or a module function that's suitable, you don't
1027need to define a new function at all::
1028
1029 stripped_lines = [line.strip() for line in lines]
1030 existing_files = filter(os.path.exists, file_list)
1031
1032If the function you need doesn't exist, you need to write it. One way to write
Ezio Melotti45a101d2012-10-12 12:42:51 +03001033small functions is to use the :keyword:`lambda` statement. ``lambda`` takes a
1034number of parameters and an expression combining these parameters, and creates
1035an anonymous function that returns the value of the expression::
Georg Brandl4216d2d2008-11-22 08:27:24 +00001036
1037 adder = lambda x, y: x+y
1038
Ezio Melotti45a101d2012-10-12 12:42:51 +03001039 print_assign = lambda name, value: name + '=' + str(value)
1040
Georg Brandl4216d2d2008-11-22 08:27:24 +00001041An alternative is to just use the ``def`` statement and define a function in the
1042usual way::
1043
Ezio Melotti45a101d2012-10-12 12:42:51 +03001044 def adder(x, y):
1045 return x + y
Georg Brandl4216d2d2008-11-22 08:27:24 +00001046
1047 def print_assign(name, value):
1048 return name + '=' + str(value)
1049
Georg Brandl4216d2d2008-11-22 08:27:24 +00001050Which alternative is preferable? That's a style question; my usual course is to
1051avoid using ``lambda``.
1052
1053One reason for my preference is that ``lambda`` is quite limited in the
1054functions it can define. The result has to be computable as a single
1055expression, which means you can't have multiway ``if... elif... else``
1056comparisons or ``try... except`` statements. If you try to do too much in a
1057``lambda`` statement, you'll end up with an overly complicated expression that's
Ezio Melotti45a101d2012-10-12 12:42:51 +03001058hard to read. Quick, what's the following code doing? ::
Georg Brandl4216d2d2008-11-22 08:27:24 +00001059
1060 import functools
1061 total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
1062
1063You can figure it out, but it takes time to disentangle the expression to figure
1064out what's going on. Using a short nested ``def`` statements makes things a
1065little bit better::
1066
1067 import functools
Ezio Melotti45a101d2012-10-12 12:42:51 +03001068 def combine(a, b):
Georg Brandl4216d2d2008-11-22 08:27:24 +00001069 return 0, a[1] + b[1]
1070
1071 total = functools.reduce(combine, items)[1]
1072
1073But it would be best of all if I had simply used a ``for`` loop::
1074
1075 total = 0
1076 for a, b in items:
1077 total += b
1078
1079Or the :func:`sum` built-in and a generator expression::
1080
1081 total = sum(b for a,b in items)
1082
1083Many uses of :func:`functools.reduce` are clearer when written as ``for`` loops.
1084
1085Fredrik Lundh once suggested the following set of rules for refactoring uses of
1086``lambda``:
1087
Ezio Melotti45a101d2012-10-12 12:42:51 +030010881. Write a lambda function.
10892. Write a comment explaining what the heck that lambda does.
10903. Study the comment for a while, and think of a name that captures the essence
Georg Brandl4216d2d2008-11-22 08:27:24 +00001091 of the comment.
Ezio Melotti45a101d2012-10-12 12:42:51 +030010924. Convert the lambda to a def statement, using that name.
10935. Remove the comment.
Georg Brandl4216d2d2008-11-22 08:27:24 +00001094
Georg Brandl48310cd2009-01-03 21:18:54 +00001095I really like these rules, but you're free to disagree
Georg Brandl4216d2d2008-11-22 08:27:24 +00001096about whether this lambda-free style is better.
1097
1098
Georg Brandl116aa622007-08-15 14:28:22 +00001099Revision History and Acknowledgements
1100=====================================
1101
1102The author would like to thank the following people for offering suggestions,
1103corrections and assistance with various drafts of this article: Ian Bicking,
1104Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
1105Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
1106
1107Version 0.1: posted June 30 2006.
1108
1109Version 0.11: posted July 1 2006. Typo fixes.
1110
1111Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one.
1112Typo fixes.
1113
1114Version 0.21: Added more references suggested on the tutor mailing list.
1115
1116Version 0.30: Adds a section on the ``functional`` module written by Collin
1117Winter; adds short section on the operator module; a few other edits.
1118
1119
1120References
1121==========
1122
1123General
1124-------
1125
1126**Structure and Interpretation of Computer Programs**, by Harold Abelson and
1127Gerald Jay Sussman with Julie Sussman. Full text at
1128http://mitpress.mit.edu/sicp/. In this classic textbook of computer science,
1129chapters 2 and 3 discuss the use of sequences and streams to organize the data
1130flow inside a program. The book uses Scheme for its examples, but many of the
1131design approaches described in these chapters are applicable to functional-style
1132Python code.
1133
1134http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
1135programming that uses Java examples and has a lengthy historical introduction.
1136
1137http://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
1138describing functional programming.
1139
1140http://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
1141
1142http://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
1143
1144Python-specific
1145---------------
1146
1147http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
1148:title-reference:`Text Processing in Python` discusses functional programming
1149for text processing, in the section titled "Utilizing Higher-Order Functions in
1150Text Processing".
1151
1152Mertz also wrote a 3-part series of articles on functional programming
Georg Brandl48310cd2009-01-03 21:18:54 +00001153for IBM's DeveloperWorks site; see
Sandro Tosi1abde362011-12-31 18:46:50 +01001154`part 1 <http://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
1155`part 2 <http://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
1156`part 3 <http://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158
1159Python documentation
1160--------------------
1161
1162Documentation for the :mod:`itertools` module.
1163
1164Documentation for the :mod:`operator` module.
1165
1166:pep:`289`: "Generator Expressions"
1167
1168:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
1169features in Python 2.5.
1170
1171.. comment
1172
1173 Topics to place
1174 -----------------------------
1175
1176 XXX os.walk()
1177
1178 XXX Need a large example.
1179
1180 But will an example add much? I'll post a first draft and see
1181 what the comments say.
1182
1183.. comment
1184
1185 Original outline:
1186 Introduction
1187 Idea of FP
1188 Programs built out of functions
1189 Functions are strictly input-output, no internal state
1190 Opposed to OO programming, where objects have state
1191
1192 Why FP?
1193 Formal provability
1194 Assignment is difficult to reason about
1195 Not very relevant to Python
1196 Modularity
1197 Small functions that do one thing
1198 Debuggability:
1199 Easy to test due to lack of state
1200 Easy to verify output from intermediate steps
1201 Composability
1202 You assemble a toolbox of functions that can be mixed
1203
1204 Tackling a problem
1205 Need a significant example
1206
1207 Iterators
1208 Generators
1209 The itertools module
1210 List comprehensions
1211 Small functions and the lambda statement
1212 Built-in functions
1213 map
1214 filter
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216.. comment
1217
1218 Handy little function for printing part of an iterator -- used
1219 while writing this document.
1220
1221 import itertools
1222 def print_iter(it):
1223 slice = itertools.islice(it, 10)
1224 for elem in slice[:-1]:
1225 sys.stdout.write(str(elem))
1226 sys.stdout.write(', ')
Georg Brandl6911e3c2007-09-04 07:15:32 +00001227 print(elem[-1])
Georg Brandl116aa622007-08-15 14:28:22 +00001228
1229